![](/img/trans.png)
[英]How to set the Google Map zoom level to show all the markers and user at center?
[英]How to set the Google Map zoom level to show all the markers?
如何設置縮放級別以顯示Google地圖上的所有標記?
在我的Google地圖中,不同位置有不同的標記。 我想根據標記的范圍設置谷歌地圖縮放級別(這意味着在谷歌地圖的視圖中,我想看到所有標記)
你去:
<!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>
我們在上面的例子中創建了10個隨機點,然后將每個點傳遞給GLatLngBounds.extend()
。 最后,我們使用GMap2.getBoundsZoomLevel()
獲得正確的縮放級別。
如果您使用的是API版本3,則可以替換
map.setCenter(markerBounds.getCenter(), map.getBoundsZoomLevel(markerBounds));
同
map.fitBounds(markerBounds).
設置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);
上面的代碼將自動居中並縮放地圖,以便所有標記都可見。
您可以使用GLatLngBounds對象的extend
方法,該方法表示地圖上的矩形。
var bounds = new GLatLngBounds();
循環遍歷地圖上的所有點 ,為每個點擴展GLatLngBounds對象的邊界。
bounds.extend(myPoint);
最后,您可以使用bounds對象設置地圖的中心和縮放( map
是地圖對象)
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.