Javascript 如果Geocoder返回零结果,则Maps API v3获取半径内最近的位置
我正在尝试使用地理定位API和GoogleMapsGeocoder获取格式化的用户地址。这一切都很好,但不是每个地方都能做到。例如,对于latitude42.6462539 21.1784982999998返回零结果。。。如果您查看地图,这些坐标周围的区域有足够的数据,因此是否有可能获得给定半径(例如250米)内的近似地址,例如最近的道路或地点 以下是我当前的代码:Javascript 如果Geocoder返回零结果,则Maps API v3获取半径内最近的位置,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我正在尝试使用地理定位API和GoogleMapsGeocoder获取格式化的用户地址。这一切都很好,但不是每个地方都能做到。例如,对于latitude42.6462539 21.1784982999998返回零结果。。。如果您查看地图,这些坐标周围的区域有足够的数据,因此是否有可能获得给定半径(例如250米)内的近似地址,例如最近的道路或地点 以下是我当前的代码: if (!navigator.geolocation) alert('Geolocation is not supported b
if (!navigator.geolocation) alert('Geolocation is not supported by this browser.');
navigator.geolocation.getCurrentPosition(function(position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
geocoder.geocode({latLng: latlng}, function(results, status) {
if (status === 'OK') {
console.log('Geocoding successful.', results);
} else {
console.log('Geocoding failed...', status);
}
});
});
谢谢 地理编码似乎在您所在的地区不起作用,即使是在附近的其他坐标中。您可以检查状态并使用另一种方法查找最近的位置
if (status == google.maps.GeocoderStatus.OK) {
// Success
} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
// Try something else
}
一个解决方案是,例如。对于您的示例坐标,它是有效的
https://roads.googleapis.com/v1/nearestRoads?points=42.6462539,21.178498299999998&key=your_api_key
您必须在Google开发者控制台中启用API,并提供自己的密钥
上述查询返回:
{
"snappedPoints": [
{
"location": {
"latitude": 42.646445887532415,
"longitude": 21.178424485523163
},
"originalIndex": 0,
"placeId": "ChIJwzaWjcieVBMR-DmaAxrqIs8"
},
{
"location": {
"latitude": 42.646445887532415,
"longitude": 21.178424485523163
},
"originalIndex": 0,
"placeId": "ChIJwzaWjcieVBMR-TmaAxrqIs8"
}
]
}
然后使用返回的placeId
你也可以试试,这取决于你的目标。“邻近搜索”接受半径参数。邻近搜索方法执行了此操作。谢谢
geocoder.geocode({
'placeId': 'ChIJwzaWjcieVBMR-DmaAxrqIs8'
}, function (results, status) {
// Returns "Muharrem Fejza, Prishtinë"
});