简体   繁体   中英

How to Set Zoom of Map to cover all markers visible Markers?

I have created a map with markers which are fetching latlongs data from mongodb collection.I have set the center as a particular location and zoom level to 5 but I want the map should zoom-in or zoom-out based on marker's location.So that I dont have to give any particular location in center. Please help.

The Code is below -

 <div class="page-content">
            <div id="tab-general">
              <div id="map" style="height: 500px; width: 100%;">

              </div> 
            </div>
 </div>

 <script type="text/javascript">
//LOAD DATA FROM MONGO
       data= <%-JSON.stringify(data)%>

 </script>
 <script type="text/javascript">

 var LatLngs = [];
  for (j=0;j<data.length;j++){

     LatLngs[j] = [data[j].latitude, data[j].longitude, data[j].time, data[j].name];

  }

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

var infowindow = new google.maps.InfoWindow();

var marker, i ,ext;


for (i = 0; i < LatLngs.length; i++) { 
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(LatLngs[i][0], LatLngs[i][1]),
    map: map
  });

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent("Time - "+LatLngs[i][2]+"<br>User Name -"+LatLngs[i][3]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

Thanks,

Dia

What you do is create a LatLngBounds object. As you add each marker, you expand the bounds to include that marker's location. After all the markers are added, you then update the map to fit those bounds, and it will adjust its zoom automatically so all the markers are visible.

var bounds = new google.maps.LatLngBounds();

for (i = 0; i < LatLngs.length; i++) {
    position = new google.maps.LatLng(LatLngs[i][0], LatLngs[i][1]);

    marker = new google.maps.Marker({
        position: position,
        map: map
    });

    bounds.extend(position)
}

map.fitBounds(bounds);

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