简体   繁体   中英

Google Maps API Places Search get number of search results

I have implemented a sample using Places Search of Google Maps API. I would like to fetch the number of results I am fetching. New to Google Maps API. How do I achieve this?

jsFiddle

JS:

var map;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(19.107567, 72.8335);

  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: pyrmont,
    zoom: 15
  });

  var request = {
    location: pyrmont,
    radius: 500,
    types: ['hospital']
  };
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

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

google.maps.event.addDomListener(window, 'load', initialize);

Replace your callback with this:

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    // Just count the number of results passed to your callback
    var numResults = results.length;

    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM