Javascript 自动调整缩放以适应谷歌地图中的所有标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3897744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automatically adjust zoom to accommodate all marker in a google map
提问by TrustyCoder
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?
使用最新版本的谷歌地图。如何使用经纬度添加标记并使用 JavaScript 自动调整地图的缩放级别以包含所有标记?
回答by Salman A
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:
Google Maps API v3 提供了一个LatLngBounds
对象,您可以向其中添加多个LatLng
对象。然后,您可以将其传递给Map.fitBounds()
函数,如下所述:
- 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);
回答by RedBlueThing
You add markers to your google map by instantiating a markerobject for each of your latitude/longitude pairs:
您可以通过为每个纬度/经度对实例化一个标记对象来向您的 google 地图添加标记:
var marker = new google.maps.Marker({
position: currentLatLng,
map: map,
title:"Title!"
});
The mapoption 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 fitBoundsmethod on the mapobject. fitBounds takes a latLngBoundsobject as a parameter. This object has a handy extendmethod which will adjust the bounds to include a new latitude/longitude. So you just need to spin through all your points, calling extendon 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 fitBoundsmethod on the mapand it will zoom to show all your new markers.
要缩放地图以包含新标记,请在地图对象上使用fitBounds方法。fitBounds 将latLngBounds对象作为参数。这个对象有一个方便的扩展方法,它将调整边界以包括新的纬度/经度。因此,您只需要遍历所有点,在单个 latLngBounds 对象上调用扩展。这将扩展边界以包括您的所有标记。完成此操作后,将此对象传递给地图上的fitBounds方法,它会缩放以显示所有新标记。
回答by Jose Mhlanga
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
在 setZoom() 方法中设置所需的缩放比例。值越大,显示位置细节越广,值越小,它会限制和缩小位置细节