使用谷歌地理编码api jquery从经度和纬度获取城市名称 [英] get city name from longitude and latitude using google geocoding api jquery
问题描述
我想从经度和纬度获得城市名称.我正在使用以下代码,但是它将返回带有城市名称,邮政编码,省和国家/地区的整个地址.我只想要城市名称.
I want to get city name from longitude and latitude. I am using following code but it is returning the entire address with city name, postal code, province and country. I just want only city name.
$.ajax({ url:'http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude+'&sensor=true',
success: function(data){
alert(data.results[4].formatted_address);
}
});
请查看地理编码的结果
{
"long_name" : "Vancouver",
"short_name" : "Vancouver",
"types" : [ "locality", "political" ]
},
由于API数据类型的性质,
推荐答案
formatted_address总是会返回完整的地址字符串.您需要直接在address_components数组中引用位置类型.
formatted_address is always going to return you a full address string, due to the nature of the datatype from the API. You need to directly reference the locality type in the address_components array.
例如,您需要在返回的address_components数组中搜索位置类型:
So for example, you need to search through the returned address_components array for the locality type:
for (var i = 0; i < data.results[4].address_components.length; i++) {
for (var j = 0; j < data.results[4].address_components[i].types.length; j++) {
if(data.results[4].address_components[i].types[j] == 'locality') {
var city_name = data.results[4].address_components[i].long_name;
alert(city_name);
}
}
}
这篇关于使用谷歌地理编码api jquery从经度和纬度获取城市名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!