简体   繁体   English

如何设置地图缩放以覆盖可见标记的所有标记?

[英]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. 我创建了一个带有标记的地图,这些标记从mongodb集合中获取latlongs数据。我已将中心设置为特定位置并将缩放级别设置为5但我希望地图应根据标记的位置放大或缩小。所以我不必在中心给任何特定的位置。 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. 你要做的是创建一个LatLngBounds对象。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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