سؤال

My Google maps API map zooms put to show all the markers added after a google places search. On a mobile map this can take a bit to load and as this app for cyclists I prefer to only show the results within the viewport. Most research I read indicates it is not possible to only return results within the view port. Is it possible for me to just keep the map bounds from changing after the markers are added? It would be great if it would just show me the markers added to the current bounds unless there is only one marker returned, then it should zoom to that marker. So searching for something general like pizza will show many pizza places in the current viewport without panning or zooming. Searching for a specific address will zoom to that marker even if it is outside the viewport.

 var input = document.getElementById('target');
 var searchBox = new google.maps.places.SearchBox(input);
 var bounds = map.getBounds();
 searchBox.setBounds(bounds);
 var markers = [];
 service = new google.maps.places.PlacesService(map);

 google.maps.event.addListener(searchBox, 'places_changed', function() {
     var places = searchBox.getPlaces();
     // alert("getPlaces returns "+places.length+" places");

     for (var i = 0; i < gmarkers.length; i++) {
       gmarkers[i].setMap(null);
     }

     gmarkers = [];
     var bounds = new google.maps.LatLngBounds();

     for (var i = 0, place; place = places[i]; i++) {
       var place = places[i];
       createMarker(place);
       bounds.extend(place.geometry.location);
     }
     map.fitBounds(bounds);
     // if (markers.length == 1) map.setZoom(17);
   });

   google.maps.event.addListener(map, 'bounds_changed', function() {
     var bounds = map.getBounds();
     searchBox.setBounds(bounds);
   });

   ib = new InfoBox({});
هل كانت مفيدة؟

المحلول

The answer to your question:

  • it possible for me to just keep the map bounds from changing after the markers are added?

is yes. And as you say, involves removing the map.fitBounds.

To get the map to center and zoom on a single address, either use the geocoder for that (implement it separately) or check the number of results, if it is one, center the map on the result and if there is a suggested viewport in the result, use that to center and zoom the map [with map.fitBounds(place.geometry.viewport) I think].

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top