Find nearest known location: Google Reverse Geocoding

折月煮酒 提交于 2019-12-23 03:34:08

问题


I am required to get the formatted address of a given coordinates using Google Maps API. I use the Google Reverse Geo coding for finding the location name. This works fine when there is a name available for the location in the Google maps database.

Most of the times, the given coordinates are from a location far off from city boundaries (on a highway for example). The function returns ZERO_RESULTS as there is no name defined on the map. Requirement is to find the nearest known location address to be returned.

Functionally this is a nice to hear, but technically, how to go about it?

Currently I am finding the location which is few (kilo)meters away from this point, checking if the location has a name, and recursively going till i get a name.

Personally, didn't like this approach because of the following reasons:

  1. Can't guess which direction to go to find the location which has a name

  2. I might go in a direction but a known place is just few meters in the reverse direction.

  3. I might go too far during the increment, as in a place which is 15 kms away has a name. I search for the name 10 kms away and check at 20 kms again as the increment identity is 10 kms.

The following is the complete code, which is working but with the above issues.

<!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>

would really appreciate if anyone has a good solution.

JSFiddle Link: https://jsfiddle.net/hbybs68q/1/

thanks.


回答1:


You need to modify the if condition inside getLocation function. Check for results[0] not result[1].

if (status == google.maps.GeocoderStatus.OK) {
      if (results[0]) {
            document.getElementById('spanId').innerHTML = results[0].formatted_address + ', ' + distance + ' kms away from original point' ;
      } else {
              window.alert('No results found');
      }
} else {
       window.alert('Geocoder failed due to - ' + status)
}



回答2:


ZERO_RESULTS from Reverse Geocoding in the Google Geocoding API typically mean the latlng is in a body water far off shore (oceans, seas, really big lakes, etc.) or in an area with a territorial dispute. This is a known issue: https://code.google.com/p/gmaps-api-issues/issues/detail?id=8783



来源:https://stackoverflow.com/questions/31875483/find-nearest-known-location-google-reverse-geocoding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!