Reputation: 173
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".
Upvotes: 1
Views: 6139
Reputation: 880
As per October 2018, Google has added the initial location as part of the nearbySearch, as follows:
service.nearbySearch({
location: place.geometry.location, //Add initial lat/lon here
rankBy: google.maps.places.RankBy.DISTANCE,
type: ['museum']
}, callback);
The aforementioned code will return the museums close to the location specified ordered by distance asc. Find more info here: https://developers.google.com/maps/documentation/javascript/examples/place-search
Upvotes: 0
Reputation: 33
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 Place
classes 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;
}
Upvotes: 2