在查询时,Google将API放置API可以返回一个对象而不是一系列对象



我正在与Google Places API一起玩,我想知道是否只能返回最接近的结果。在下面的示例中,我可以在半径1公里的半径内退还所有体育馆。似乎API正在返回半径内的所有对象,并且无法更改。我似乎找不到任何强调这个问题的文档,而我进行的任何尝试仍然返回该地区的所有位置。

 function GymReport(){
  // Gets the latitude and longitude of a location searched by a user
  $('.search_latitude').val(marker.getPosition().lat());
  $('.search_longitude').val(marker.getPosition().lng());
 var Lat = marker.getPosition().lat();
 console.log(Lat);
 var Long = marker.getPosition().lng();
 console.log(Long);
 var location = {lat: Lat, lng: Long};
   var service = new google.maps.places.PlacesService(map);
   service.nearbySearch({
       location: location,
       radius: 1000,
       type: ['gym']
     }, callback);
    }

回调类

 function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
      if(marker)
            marker.setMap(null)
     for (var i = 0; i < results.length; i++) { 
          createMarker(results[i]);<-- This calls the function that will create the markers for the array of results from the API.
        }
  }
}

请注意,您可以通过突出或距离订购附近搜索的位置的结果。默认情况下,它是按突出的顺序排列的。您可以使用代码中的rankBy参数按距离订购:

rankby - 指定返回结果时使用的排名方法。默认值为突出。请注意,当Rankby设置为距离时,您必须指定位置,但不能指定半径或界限。

来源:https://developers.google.com/maps/documentation/javascript/3.exp/reference#placesearchrequest

获得距离订购的结果后,只需从数组中获取第一个元素,该元素是最近的位置。看看我的示例代码

var map;
var infowindow;
function initMap() {
  var pyrmont = {lat: -33.867, lng: 151.195};
  map = new google.maps.Map(document.getElementById('map'), {
    center: pyrmont,
    zoom: 15
  });
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch({
    location: pyrmont,
    rankBy: google.maps.places.RankBy.DISTANCE,
    type: ['gym']
  }, callback);
}
function callback(results, status) {
  if (status === google.maps.places.PlacesServiceStatus.OK) {
    //Get the first result, it's the closest one
    createMarker(results[0]);
  }
}
function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });
  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name);
    infowindow.open(map, this);
  });
}
#map {
  height: 100%;
}
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&libraries=places&callback=initMap" async defer></script>

我希望这会有所帮助!

相关内容

最新更新