3

I know I can find the closes supermarkets with the google api like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.360229, 6.042169&radius=3000&type=supermarket&key=myKey

But now I get many results. How do I only get the closest one ?

Jenssen
  • 1,801
  • 4
  • 38
  • 72

2 Answers2

3

you can use rankby option with distance parameter

var request = {
  location: gps,
  types: ['grocery'],
  rankBy: google.maps.places.RankBy.DISTANCE, 
  key: key 
};

reference : https://developers.google.com/places/web-service/search

once you have multiple location use haversine formula to get the distance between two locations.

 function distance(p1, p2) {
      if (!p1 || !p2) 
       return 0;
      var R = 6371000; // Radius of the Earth in m
      var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
      var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
      var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
      Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
      Math.sin(dLon / 2) * Math.sin(dLon / 2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      var d = R * c;
      return d;
     }

reference : https://www.movable-type.co.uk/scripts/latlong.html

Shiv Kumar Baghel
  • 2,464
  • 6
  • 18
  • 34
  • Thanks but then I still get multiple results. I only want 1 result! – Jenssen Oct 12 '18 at 17:51
  • then you can find shortest distance out of array of results. you have to find the distance between two points(locations). have a look into https://stackoverflow.com/questions/1502590/calculate-distance-between-two-points-in-google-maps-v3 – Shiv Kumar Baghel Oct 12 '18 at 17:54
0

This works for me

  https://maps.googleapis.com/maps/api/place/nearbysearch/json? 
     location=51.360229,6.042169&radius=3000&type=grocery&key=vaquarkhan&rankBy? 
        google.maps.places.RankBy.DISTANCE 
vaquar khan
  • 10,864
  • 5
  • 72
  • 96