[英]How to Set Zoom of Map to cover all markers visible Markers?
我創建了一個帶有標記的地圖,這些標記從mongodb集合中獲取latlongs數據。我已將中心設置為特定位置並將縮放級別設置為5但我希望地圖應根據標記的位置放大或縮小。所以我不必在中心給任何特定的位置。 請幫忙。
守則如下 -
<div class="page-content">
<div id="tab-general">
<div id="map" style="height: 500px; width: 100%;">
</div>
</div>
</div>
<script type="text/javascript">
//LOAD DATA FROM MONGO
data= <%-JSON.stringify(data)%>
</script>
<script type="text/javascript">
var LatLngs = [];
for (j=0;j<data.length;j++){
LatLngs[j] = [data[j].latitude, data[j].longitude, data[j].time, data[j].name];
}
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(23.2500, 77.4170),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i ,ext;
for (i = 0; i < LatLngs.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(LatLngs[i][0], LatLngs[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("Time - "+LatLngs[i][2]+"<br>User Name -"+LatLngs[i][3]);
infowindow.open(map, marker);
}
})(marker, i));
}
謝謝,
迪亞
你要做的是創建一個LatLngBounds對象。 添加每個標記時,可以展開邊界以包含該標記的位置。 添加完所有標記后,您可以更新地圖以適應這些邊界,並自動調整其縮放,以便所有標記都可見。
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < LatLngs.length; i++) {
position = new google.maps.LatLng(LatLngs[i][0], LatLngs[i][1]);
marker = new google.maps.Marker({
position: position,
map: map
});
bounds.extend(position)
}
map.fitBounds(bounds);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.