New*_*wtt 5 javascript google-maps google-maps-api-3
使用Google Maps Geocoding API,我可以获取特定坐标的格式化地址.要获得确切的城市名称,我正在执行以下操作:
$.ajax({
url: 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&sensor=false',
success: function(data){
var formatted = data.results;
var address_array = formatted[6].formatted_address.split(',');
var city = address_array[0];
}
});
Run Code Online (Sandbox Code Playgroud)
where lat和long是使用浏览器坐标派生的.我的问题如下:
从坐标19.2100和72.1800,我得到这个城市的Mumbai,而是从一组类似3km左右的坐标了,我得市Mumbai Suburban.如何在Mumbai不更改代码的成功功能的情况下获得?在我看来,结果数组并不总是坚持使用相同的格式,这会在我显示城市名称时产生问题.
所以我今天试图解决这个问题,如果它对任何人有帮助,我就会找到这个解决方案。谷歌地图现在内置了地理编码器,因此您只需在 API 加载后创建地理编码器对象。
您可以轻松地将其包装在一个函数中,然后只返回一个包含城市、州和邮政编码的对象。该站点有助于我了解不同“类型”的含义: 反向地理编码
var geocoder = new google.maps.Geocoder,
latitude = 28.54, //sub in your latitude
longitude = -81.39, //sub in your longitude
postal_code,
city,
state;
geocoder.geocode({'location': {lat:latitude, lng:longitude}}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
results.forEach(function(element){
element.address_components.forEach(function(element2){
element2.types.forEach(function(element3){
switch(element3){
case 'postal_code':
postal_code = element2.long_name;
break;
case 'administrative_area_level_1':
state = element2.long_name;
break;
case 'locality':
city = element2.long_name;
break;
}
})
});
});
}
});
Run Code Online (Sandbox Code Playgroud)
您需要查看结果的类型,而不是结果数组中的绝对索引。迭代结果数组,查找具有适当类型的条目。看起来是这样的:
但数据可能因地区而异。
相关问题:Grabing Country from google geocode jquery
看起来您想要同时具有“地方”和“政治”类型的条目:
{
"long_name" : "Mumbai",
"short_name" : "Mumbai",
"types" : [ "locality", "political" ]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5110 次 |
| 最近记录: |