I'm trying to return to separate string in this if statement and not as a single string. one as a latitude and the other as longitude
static string GeoCoding(string address)
{
var json = new WebClient().DownloadString(baseUrlGC address.Replace(" ", " ")
plusUrl);//concatenate URL with the input address and downloads the requested resource
GoogleGeoCodeResponse jsonResult = JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(json); //deserializing the result to GoogleGeoCodeResponse
string status = jsonResult.status; // get status
string geoLocation = String.Empty;
//check if status is OK
if (status == "OK")
{
for (int i = 0; i < jsonResult.results.Length;i ) //loop throught the result for lat/lng
{
geoLocation = jsonResult.results[i].geometry.location.lat jsonResult.results[i].geometry.location.lng Environment.NewLine; //append the result addresses to every new line
}
return geoLocation; //return result
}
else
{
return status; //return status / error if not OK
}
}
CodePudding user response:
Assuming your expected result is 2 string: Latitude Longitude and a code when there is error. I would suggest you create a new
class GeoResponse{
List<(string, string)> geocodeList;
string status;
}
and change return type of your method to
static GeoResponse GeoCoding(string address)
{
var json = new WebClient().DownloadString(baseUrlGC address.Replace(" ", " ")
plusUrl);//concatenate URL with the input address and downloads the requested resource
GoogleGeoCodeResponse jsonResult = JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(json); //deserializing the result to GoogleGeoCodeResponse
GeoResponse result = new GeoResponse();
result.status = jsonResult.status; // get status
//check if status is OK
if (status == "OK")
{
for (int i = 0; i < jsonResult.results.Length; i ) //loop throught the result for lat/lng
{
result.geocodeList.Add(jsonResult.results[i].geometry.location.lat, jsonResult.results[i].geometry.location.lng);
}
}
return result;
}
CodePudding user response:
If you would like to return with all lat-long pairs (without creating a new data structure) when status
is ok
and throw an exception when status
was not ok
then you can do that like this:
static List<Tuple<string, string>> GeoCoding(string address)
{
var json = new WebClient().DownloadString($"...");
var jsonResult = JsonConvert.DeserializeObject<GoogleGeoCodeResponse>(json);
if (jsonResult.status != "OK")
throw new Exception($"Request failed with {jsonResult.status}");
return jsonResult.results
.Select(result => result.geometry.location)
.Select(loc => new Tuple<string, string>(loc.lat, loc.lng))
.ToList();
}
If you can use ValueTuple
then you could rewrite the code like this:
static List<(string Lat, string Long)> GeoCoding(string address)
{
...
return jsonResult.results
.Select(result => result.geometry.location)
.Select(loc => (loc.lat, loc.lng))
.ToList();
}
Please also note that WebClient
is deprecated so please prefer HttpClient
instead.