Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 908
Dia Sarkar Avatar asked Sep 30 '15 07:09

Dia Sarkar


People also ask

How do you zoom all the way on a map?

Zoom in the mapDouble tap a spot on the map, and then: Drag down to zoom in. Drag up to zoom out.

How do I show all pins on Google Maps?

Click on the Google Map menu item, and then click on the Settings tab. You will then see the option to Show all locations. Click to enable this option and Save.

How do you calculate zoom level on a map?

Convert latitude, longitude to spherical mercator x, y. Get distance between your two points in spherical mercator. The equator is about 40m meters long projected and tiles are 256 pixels wide, so the pixel length of that map at a given zoom level is about 256 * distance/40000000 * 2^zoom.


1 Answers

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);
like image 76
duncan Avatar answered Oct 06 '22 00:10

duncan