我正在尝试通过 jquery ajax 从 google map 检索某个位置的纬度和经度。
这是我的 JavaScript 代码:
var lat;
var lng;
function setCordinates(address)
{
var ret = false;
data = "address="+address;
$.ajax({
type: "GET",
url: "https://maps.googleapis.com/maps/api/geocode/json",
data: data,
cache: false,
dataType: 'json',
success: function(json_data)
{
lat = json_data.results.geometry.location.lat;
lng = json_data.results.geometry.location.lng;
ret = true;
},
error: function()
{
alert("There was an error!");
}
});
return ret;
}
当我从控制台预览响应正文时,我得到的 json 数据返回为:
{
"results" : [
{
"address_components" : [
{
"long_name" : "Uyo",
"short_name" : "Uyo",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Akwa Ibom",
"short_name" : "Akwa Ibom",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "Nigeria",
"short_name" : "NG",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Uyo, Nigeria",
"geometry" :
{
"bounds" :
{
"northeast" :
{
"lat" : 5.0906023,
"lng" : 8.0030251
},
"southwest" :
{
"lat" : 4.9681658,
"lng" : 7.8638077
}
},
"location" :
{
"lat" : 5.0377396,
"lng" : 7.9127945
},
"location_type" : "APPROXIMATE",
"viewport" :
{
"northeast" :
{
"lat" : 5.0906023,
"lng" : 8.0030251
},
"southwest" :
{
"lat" : 4.9681658,
"lng" : 7.8638077
}
}
},
"partial_match" : true,
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
我试图从位置获取纬度和经度的值,但出现错误:
TypeError: json_data.results.geometry is undefined
我看过this post , this post , this post , this post和 this post但我真的不知道该怎么办。它们看起来都毫无关联。请帮助我对 json 还很陌生。谢谢。
最佳答案
这个怎么样:
lat = json_data.results[0].geometry.location.lat;
lng = json_data.results[0].geometry.location.lng;
关于javascript - 如何从 json 中检索这些值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26567505/