Automatically adjust zoom to accommodate all marker in a google map

一曲冷凌霜 提交于 2019-11-28 22:04:05

问题


Using the latest version of Google maps. How to add markers using longitude and latitude and automatically adjust the zoom level of the map to include all the markers using JavaScript?


回答1:


Google Maps API v3 provides a LatLngBounds object to which you can add multiple LatLng objects. You can then pass this to Map.fitBounds() function as described here:

  • Zoom-To-Fit All Markers, Polylines or Polygons on A Google Map - API v2
  • Zoom-to-Fit All Markers on Google Map v3

Partial Example

var latlng = [
    new google.maps.LatLng(1.23, 4.56),
    new google.maps.LatLng(7.89, 1.01),
    // ...
]; 
var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
    latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);



回答2:


You add markers to your google map by instantiating a marker object for each of your latitude/longitude pairs:

var marker = new google.maps.Marker({
    position: currentLatLng, 
    map: map,
    title:"Title!"
}); 

The map option on the marker constructer will associate the new market object with your map.

To zoom your map to include your new markers, you use the fitBounds method on the map object. fitBounds takes a latLngBounds object as a parameter. This object has a handy extend method which will adjust the bounds to include a new latitude/longitude. So you just need to spin through all your points, calling extend on a single latLngBounds object. This will extend the bounds to include all your markers. Once you have done this, you pass this object into the fitBounds method on the map and it will zoom to show all your new markers.




回答3:


The following did the trick for me

map.fitBounds(bounds);


 // add a zoom to the map


var listener = google.maps.event.addListener(map, 'idle', function()
        {
          if(map.getZoom() > 16)
            map.setZoom(17);
          google.maps.event.removeListener(listener);
        });

Set your desired zoom in the setZoom() method. The larger the value, the wider it shows location details, the smaller the value, it throttles and shrinks the location details



来源:https://stackoverflow.com/questions/3897744/automatically-adjust-zoom-to-accommodate-all-marker-in-a-google-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!