Google Map Zoom To Fit

2019-08-23 03:33发布

问题:

I have developed a map that uses a geo-coordinate from a database using a cluster marker example. I have tried to make it zoom automaticly by using LatLngBounds();

 <script type="text/javascript">
     function initialize() {
            var center = new google.maps.LatLng(9.4419, 9.1419);

            var map = new google.maps.Map(document.getElementById('map'), {
              zoom: 2,
              center: center,
              mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var markers = [];
            // create the infowindow out of the for boucle
            var infoWindow = new google.maps.InfoWindow;
            var bounds = new google.maps.LatLngBounds();

for ( var i = 0; i < latlng.length; i++ ) {

      var latLng = new google.maps.LatLng(latlng.lat,latlng.lng);   

     var html = 'test show in infowondow';

    var marker = new google.maps.Marker({
            position: latLng,
            map: map,
            icon:"/img/icon1.jpg",
            title:"test title",
        });
    // call to the function....
    bindInfoWindow(marker, map, infoWindow, html);
    markers.push(marker);

  }     

            var markerCluster = new MarkerClusterer(map, markers);
          }

    // create a function bindInfoWindow

    function bindInfoWindow(marker, map, infoWindow, html) {
          google.maps.event.addListener(marker, 'click', function() {
            infoWindow.setContent(html);
            infoWindow.open(map, marker);
          });
    }

            var markerCluster = new MarkerClusterer(map, markers);
          }
          google.maps.event.addDomListener(window, 'load', initialize);
        </script>

回答1:

  • make bounds global.
  • then after

var latLng = new google.maps.LatLng(latlng.lat,latlng.lng);

EDIT: and as Marcelo pointed out change this to:

var latLng = new google.maps.LatLng(latlng[i].lat,latlng[i].lng);

add:

bounds.extend(latLng)

  • after

var markerCluster = new MarkerClusterer(map, markers);

add:

map.fitBounds(bounds);