Maps API v3如果Geocoder返回ZERO_RESULTS,则获取半径内最近的位置

时间:2017-05-04 20:57:50

标签: javascript google-maps google-maps-api-3

我正在尝试使用Geolocation APIGoogle Maps Geocoder获取格式化的用户地址。这一切都很好,但不是在每个地方。例如,my address的纬度42.6462539 21.178498299999998会返回ZERO_RESULTS ...如果您检查地图,这些坐标周围的区域有足够的数据,那么是否可以获得大致的地址,说一个给定半径内最近的道路或地点,例如250米

这是我目前的代码:

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);
        }
    });
});

谢谢!

1 个答案:

答案 0 :(得分:1)

即使使用其他附近的坐标,地理编码似乎也无法在您的区域内工作。您可以检查状态并使用其他方式找到最近的地方。

if (status == google.maps.GeocoderStatus.OK) {

    // Success

} else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {

    // Try something else
}

一种解决方案是例如Roads API。使用您的示例坐标,它可以正常工作。

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ë"
});

你也可以试试nearby search,取决于你的目标。附近的搜索接受半径参数。

相关问题