[英]How to set the Google Map zoom level to show all the markers?
How do I set the zoom level to show all the markers on Google Maps? 如何设置缩放级别以显示Google地图上的所有标记?
In my Google Map there are different markers in different positions. 在我的Google地图中,不同位置有不同的标记。 I want to set google map zoom level based on the range of markers (that means in the view of google map, i want to see all markers)
我想根据标记的范围设置谷歌地图缩放级别(这意味着在谷歌地图的视图中,我想看到所有标记)
There you go: 你去:
<!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>
We are creating 10 random points in the above example and then passing each point to GLatLngBounds.extend()
. 我们在上面的例子中创建了10个随机点,然后将每个点传递给
GLatLngBounds.extend()
。 Finally we get the correct zoom level with GMap2.getBoundsZoomLevel()
. 最后,我们使用
GMap2.getBoundsZoomLevel()
获得正确的缩放级别。
If you are using API version 3 you can replace 如果您使用的是API版本3,则可以替换
map.setCenter(markerBounds.getCenter(), map.getBoundsZoomLevel(markerBounds));
with 同
map.fitBounds(markerBounds).
set the Google Map zoom level to show all the markers?
设置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);
The code above will automaticlly center and zoom your map so that all markers are visible. 上面的代码将自动居中并缩放地图,以便所有标记都可见。
You can use the extend
method of the GLatLngBounds object, which represents a rectangle on the map. 您可以使用GLatLngBounds对象的
extend
方法,该方法表示地图上的矩形。
var bounds = new GLatLngBounds();
Loop around all the points on your map, extending the bounds of your GLatLngBounds object for each one. 循环遍历地图上的所有点 ,为每个点扩展GLatLngBounds对象的边界。
bounds.extend(myPoint);
Finally you can use your bounds object to set the centre and zoom of your map (where map
is your map object) 最后,您可以使用bounds对象设置地图的中心和缩放(
map
是地图对象)
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.