2017-05-04 64 views
0

我试图使用Geolocation APIGoogle Maps Geocoder来获取格式化的用户地址。这一切都很好,但不是在每个地方。例如,my address与纬度42.6462539 21.178498299999998返回ZERO_RESULTS ...如果您查看地图,这些坐标周围的区域具有足够的数据,那么可以在给定的半径范围内获取近似的地址(例如最近的道路或地点)例如250米Maps API v3如果Geocoder返回ZERO_RESULTS,则获取距离最近的地方

这里是我当前的代码:

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

即使使用其他附近的坐标,地理编码在您所在的区域似乎也不起作用。您可以检查状态并使用其他方式查找最近的地点。

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尝试

然后,取决于你的目标是什么。附近的搜索接受一个半径参数。

+0

附近的搜索方法做到了。谢谢! – Albion

相关问题