考虑以下示例,它将在美国东北部生成 10 个随机点,并应用该fitBounds()
方法。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps LatLngBounds.extend() Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var markerBounds = new google.maps.LatLngBounds();
var randomPoint, i;
for (i = 0; i < 10; i++) {
// Generate 10 random points within North East USA
randomPoint = new google.maps.LatLng( 39.00 + (Math.random() - 0.5) * 20,
-77.00 + (Math.random() - 0.5) * 20);
// Draw a marker for each random point
new google.maps.Marker({
position: randomPoint,
map: map
});
// Extend markerBounds with each random point.
markerBounds.extend(randomPoint);
}
// At the end markerBounds will be the smallest bounding box to contain
// our 10 random points
// Finally we can call the Map.fitBounds() method to set the map to fit
// our markerBounds
map.fitBounds(markerBounds);
</script>
</body>
</html>
多次刷新此示例,没有任何标记超出视口。有时,当隐藏在控件后面时,有时会从顶部稍微剪掉一个标记:
总是在对象和视口fitBounds()
之间留下一个小的边距也是毫无价值的。LatLngBounds
这在下面的屏幕截图中清楚地显示,其中红色边界框表示LatLngBounds
传递给fitBounds()
方法的内容:
您可能也有兴趣查看以下有关该主题的 Stack Overflow 帖子: