【发布时间】:2019-10-25 23:38:12
【问题描述】:
我无法从从谷歌地理代码 API 收到的 JSON 结果中检索值
功能
public static async Task GetLatLogFromAddress()
{
using (var client = new HttpClient())
{
Uri Inputuri = new Uri("https://maps.googleapis.com/maps/api/geocode/json?address=123+N+TRY+Street+Paul,+MN&key=APIKey");
client.BaseAddress = Inputuri;
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = await client.GetAsync(client.BaseAddress); ; // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body
string result = await response.Content.ReadAsStringAsync();
dynamic jsonData = JsonConvert.DeserializeObject<dynamic>(result);
foreach(var geo in jsonData)
{
var lat = (decimal)geo[0].geometry.location.lat;
var longi = (decimal)geo[0].geometry.location.lng;
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
client.Dispose();
}
}
JSON 格式的结果是
{
"results" : [
{
"address_components" : [
{
"long_name" : "Winnetka",
"short_name" : "Winnetka",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Los Angeles",
"short_name" : "LA",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Los Angeles County",
"short_name" : "Los Angeles County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Winnetka, Los Angeles, CA, USA",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 34.2355209,
"lng" : -118.5534191
},
"southwest" : {
"lat" : 34.1854649,
"lng" : -118.588536
}
},
"location" : {
"lat" : 34.2048586,
"lng" : -118.5739621
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 34.2355209,
"lng" : -118.5534191
},
"southwest" : {
"lat" : 34.1854649,
"lng" : -118.588536
}
}
},
"place_id" : "ChIJ0fd4S_KbwoAR2hRDrsr3HmQ",
"types" : [ "neighborhood", "political" ]
}
],
"status" : "OK"
}
这些是我们从 Google GeoCode API 获得的结果
我正在尝试获取纬度和经度,但我收到一个错误,即 Geo 不包含任何几何定义。如何访问从 google geo code API 收到的 JSON 结果?
【问题讨论】:
-
@mjwills 我用结果更新了问题。谢谢
标签: c# api model-view-controller google-geocoding-api google-geolocation