我希望我的visior输入一个城市名称,然后我可以从该名称中获得纬度和经度。我不知道如何使用谷歌地图api获取它们。我发现世界天气在线api很容易,所以我有这个json响应,但无法浏览它。
{ "search_api" : {
"result" : [
{ "areaName" : [ { "value" : "New York" } ],
"country" : [ { "value" : "United States Of America" } ],
"latitude" : "40.710",
"longitude" : "-74.010",
"population" : "8107916",
"region" : [ { "value" : "New York" } ],
"weatherUrl" : [ { "value": "http://free.worldweatheronline.com/weather/United-States-Of-America/2395340/New-York/2478232/info.aspx" } ]
},
{ "areaName" : [ { "value" : "New York" } ],
"country" : [ { "value" : "United States Of America" } ],
"latitude" : "32.170",
"longitude" : "-95.670",
"population" : "0",
"region" : [ { "value" : "Texas" } ],
"weatherUrl" : [ { "value": "http://free.worldweatheronline.com/weather/United-States-Of-America/2395340/New-York/2516758/info.aspx" } ]
}
]
}
}
这就是我尝试的:
$.getJSON(url, function(data) {
var cord = data.search_api.latitude;
alert(cord);
} );
有人能帮我解决这个问题吗?或者给我一个更好的方法,从给定的城市名称或地址获取经度和纬度?
您的代码不起作用,因为当您需要首先遍历名为result
的数组时,您试图直接从search_api
跳到latitude
,例如
$.getJSON( url, function( data ) {
var firstResult = data.search_api.result[ 0 ];
console.log( "City:", firstResult.areaName[ 0 ].value, ",",
firstResult.region[ 0 ].value
);
console.log( "Latitude:", firstResult.latitude );
console.log( "Longitude:", firstResult.longitude );
} );
/* Output:
> City: New York , New York
> Latitude: 40.710
> Longitude: -74.010
*/