【发布时间】:2015-08-07 10:24:50
【问题描述】:
我需要使用 Google Maps API 获取给定坐标的格式化地址。我使用Google Reverse Geo coding 来查找位置名称。如果 Google 地图数据库中有该位置的可用名称,则此方法可以正常工作。
大多数情况下,给定坐标来自远离城市边界的位置(例如在高速公路上)。该函数返回ZERO_RESULTS,因为地图上没有定义名称。要求是找到要返回的最近的已知位置地址。
从功能上讲,这很好听,但从技术上讲,该怎么做呢?
目前我正在寻找距离这一点几(公里)米的位置,检查该位置是否有名称,然后递归地进行直到我得到一个名称。
个人不喜欢这种方法,原因如下:
猜不出该往哪个方向去找到有名字的位置
我可能会朝一个方向走,但一个已知的地方在相反方向上只有几米。
- 在增量期间我可能会走得太远,比如在 15 岁的地方 公里外有一个名字。我在 10 公里外搜索名称并查看 又是 20 公里,因为增量标识是 10 公里。
以下是完整的代码,可以正常工作,但存在上述问题。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Map Test</title>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
</head>
<body>
<span id="spanId">Loading...</span>
<script>
Number.prototype.toRad = function () {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function () {
return this * 180 / Math.PI;
}
google.maps.LatLng.prototype.destinationPoint = function (brng, dist) {
dist = dist / 6371;
brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1),
Math.cos(dist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
var pointA = new google.maps.LatLng(32.6811,74.8732);
getLocation(pointA);
var distance = 0;
function getLocation(info) {
var myCenter = info; //new google.maps.LatLng(info.split(",", 3)[1], info.split(",", 3)[2]);
var gc = new google.maps.Geocoder();
gc.geocode({ 'location': myCenter }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
document.getElementById('spanId').innerHTML = results[1].formatted_address + ', ' + distance + ' kms away from original point' ;
} else {
window.alert('No results found');
}
} else {
if (status == 'ZERO_RESULTS' )
{
var radiusInKm = 10;
distance += radiusInKm;
document.getElementById('spanId').innerHTML = 'Getting results from ' + distance + ' kms away';
var pointB = pointA.destinationPoint(90, distance);
setTimeout(function(){
getLocation(pointB);
}, 2000);
}
}
});
}
</script>
</body>
</html>
如果有人有好的解决方案,将不胜感激。
JSFiddle 链接:https://jsfiddle.net/hbybs68q/1/
谢谢。
【问题讨论】:
标签: javascript google-maps google-maps-api-3 reverse-geocoding