Google-maps – How to sort results by distance with google places api using Nearby Search Requests

apigoogle mapsgoogle-placesgoogle-places-api

I want to get all the airport near my location order by distance. I am using Nearby Search Requests with google places api using this url : https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=51.9143924,-0.1640153&sensor=true&key=api_key&radius=50000&types=airport The results that I am getting are sparse with no order what so ever. I tried rankby=distance but no result appear.
and as per https://developers.google.com/places/documentation/search#PlaceSearchRequests documentation " radius must not be included if rankby=distance".

Best Answer

Yes, you cannot use radius and rankBy in same request. But you can use rankBy=distance and then count distance youself based on geometry.location.lat and geometry.location.lng. For exmaple in groovy i've done like that:

GeoPosition and Placeclasses are implemented by me, so don't expect to find them at the core libs :)

TreeMap<Double, Place> nearbyPlaces = new TreeMap<Double, Place>()

 if(isStatusOk(nearbySearchResponse))
                    nearbySearchResponse.results.each {

                def location = it.geometry.location
                String placeid = it.place_id
                GeoPosition position = new GeoPosition(latitude: location.lat,
                        longitude: location.lng)

                Place place =  new Place(position)

                double distance = distanceTo(place)
//If the place is actually in your radius (because Places API oftenly returns places far beyond your radius) then you add it to the TreeMap with distance to it as a key, and it will automatically sort it for you.

                if((distance <= placeSearcher.Radius()))
                    nearbyPlaces.put(distance, place)

            }

where distance is counted like that (Haversine formula):

public double distanceTo(GeoPosition anotherPos){

    int EARTH_RADIUS_KM = 6371;
    double lat1Rad = Math.toRadians(this.latitude);
    double lat2Rad = Math.toRadians(anotherPos.latitude);
    double deltaLonRad = Math.toRadians(anotherPos.longitude - this.longitude);

    return 1000*Math.acos(
                        Math.sin(lat1Rad) * Math.sin(lat2Rad) +
                        Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)
                    ) * EARTH_RADIUS_KM;
}
Related Topic