如何在谷歌地图上设置缩放级别以显示所有标记?
我的谷歌地图中有不同位置的不同标记。我想根据标记的范围设置谷歌地图的缩放级别(也就是说,在谷歌地图的视图中,我希望能够看到所有标记)。
如何在谷歌地图上设置缩放级别以显示所有标记?
我的谷歌地图中有不同位置的不同标记。我想根据标记的范围设置谷歌地图的缩放级别(也就是说,在谷歌地图的视图中,我希望能够看到所有标记)。
在这里:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps getBoundsZoomLevel Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
var markerBounds = new GLatLngBounds();
for (var i = 0; i < 10; i++) {
var randomPoint = new GLatLng( 39.00 + (Math.random() - 0.5) * 20,
-77.00 + (Math.random() - 0.5) * 20);
map.addOverlay(new GMarker(randomPoint));
markerBounds.extend(randomPoint);
}
map.setCenter(markerBounds.getCenter(),
map.getBoundsZoomLevel(markerBounds));
}
</script>
</body>
</html>
GLatLngBounds.extend()
。最后,我们使用GMap2.getBoundsZoomLevel()
获得正确的缩放级别。
如何设置Google地图的缩放级别以显示所有标记?
var markers = [markerObj1, markerObj2, markerObj3];
var newBoundary = new google.maps.LatLngBounds();
for(index in markers){
var position = markers[index].position;
newBoundary.extend(position);
}
map.fitBounds(newBoundary);
上述代码将自动居中和缩放您的地图,以便所有标记都可见。
如果您正在使用API版本3,您可以将
替换为map.setCenter(markerBounds.getCenter(), map.getBoundsZoomLevel(markerBounds));
与
map.fitBounds(markerBounds).
extend
方法,该对象表示地图上的矩形。var bounds = new GLatLngBounds();
bounds.extend(myPoint);
最后,您可以使用边界对象来设置地图的中心和缩放级别(其中map
是您的地图对象)
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));