如何使用附近的搜索请求与google places api按距离对结果进行排序

时间:2013-04-03 11:22:07

标签: api google-maps google-places-api google-places

我想通过距离让我所在机场附近的机场靠近。我正在使用谷歌地方api使用附近搜索请求使用此网址:https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=51.9143924,-0.1640153&sensor=true&key=api_key&radius=50000&types=airport我得到的结果很少,没有任何订单。我尝试了rankby = distance但没有出现结果。 并且根据https://developers.google.com/places/documentation/search#PlaceSearchRequests文档,如果rankby = distance,则不得包括半径。

3 个答案:

答案 0 :(得分:1)

是的,您不能在同一请求中使用 radius rankBy 。但您可以使用 rankBy=distance ,然后根据geometry.location.latgeometry.location.lng计算距离。对于groovy的例子,我做过这样的事情:

GeoPositionPlace类是由我实现的,所以不要指望在核心库中找到它们。)

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)

            }

其中距离计算如此(Haversine公式):

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

答案 1 :(得分:0)

您不能同时使用radiusrankby

答案 2 :(得分:0)

截至2018年10月,Google已将初始位置添加为附近搜索的一部分,如下所示:

service.nearbySearch({
  location: place.geometry.location, //Add initial lat/lon here
  rankBy: google.maps.places.RankBy.DISTANCE,
  type: ['museum']
}, callback);

上述代码将使博物馆返回按距离asc指定的位置附近。 在此处查找更多信息:https://developers.google.com/maps/documentation/javascript/examples/place-search