我正在尝试使用以下方法从JavaScript中读取JSON信息(https://maps.googleapis.com/maps/api/geocode/json?address=Mountain+View+Amphitheatre+Parkway&sensor=false):
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address="+city+"+"+steet+"&sensor=false", function(json) {
if (json.status == 'ZERO_RESULTS'){
alert('Wrong input');
}
else{
// Here I would like to read json.results.geometry.location.lat
}
});
但它不起作用。如果我尝试读取json.results,我会得到[object Object]。因为印刷json给了我同样的东西,我想我可以继续使用句号,但它没有用。
之后我尝试迭代json.results并将对象解析为数组,但都没有用。
答案 0 :(得分:2)
结果是一个对象数组。所以你应该尝试:
json.results[0].geometry.location.lat
答案 1 :(得分:1)
json.results
是一个数组,您必须访问其中的元素。
您拥有的代码正在尝试访问对象location
的属性geometry
。
但由于json.results
是一个数组,json.results.geometry
为undefined
,因此无法拥有属性。
如果您要检查控制台中的错误,您应该得到类似
的内容 Uncaught TypeError: Cannot read property 'location' of undefined
你想要的是访问results
数组的元素,因为它中的每个元素代表gMaps的一个搜索结果,然后它保存你想要访问的信息。
e.g。 json.results[0]
将为您提供代表第一个搜索结果的Object,
json.results[1]
会给你第二个,依此类推。
因此,如果您将其更改为
$.getJSON("https://maps.googleapis.com/maps/api/geocode/json?address=Berlin+Alexanderplatz&sensor=false", function(json) {
if (json.status == 'ZERO_RESULTS'){
alert('Wrong input');
}
else{
console.log(json.results[0].geometry.location.lat) // 52.5218316
}
});
您可以获得第一个结果的纬度,就像您想要的那样。
这是JSBin。
答案 2 :(得分:0)
results是一个你应该遍历的数组:
for (var i = 0; i < json.results.length; i++) {
console.log(json.results[i].geometry.location.lat);
}