Albion S.
Albion S.

Reputation: 238

Maps API v3 Get closest place within radius if Geocoder returns ZERO_RESULTS

I'm trying to get a formatted user address using Geolocation API and Google Maps Geocoder. It all works fine, but not in every place. For example, my address with latitude42.6462539 21.178498299999998 returns ZERO_RESULTS... If you check the map, the area around those coordinates has fairly enough data, so is it possible to get an approximate address, say the closest road or place, within a given radius, e.g. 250m

Here's my current code:

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

Thanks!

Upvotes: 0

Views: 501

Answers (1)

MrUpsidown
MrUpsidown

Reputation: 22486

Geocoding doesn't seem to work in your area, even with other nearby coordinates. You could check for the status and use another way to find the nearest place.

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

    // Success

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

    // Try something else
}

One solution would be for example the Roads API. With your example coordinates, it works.

https://roads.googleapis.com/v1/nearestRoads?points=42.6462539,21.178498299999998&key=your_api_key

You will have to enable the API in your Google developer console and provide your own key.

The above query returns:

{
  "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"
    }
  ]
}

Then with the returned placeId

geocoder.geocode({
  'placeId': 'ChIJwzaWjcieVBMR-DmaAxrqIs8'
  }, function (results, status) {

    // Returns "Muharrem Fejza, Prishtinë"
});

You could also try with a nearby search, depends what you aim for. The nearby search accepts a radius parameter.

Upvotes: 1

Related Questions