我有以下代码:
var bound = new google.maps.LatLngBounds();
if (arrMarkers.length > 0) {
for (var i = 0; i < arrMarkers.length; i++) {
bound.extend(new google.maps.LatLng(arrMarkers[i].getPosition().lat(), arrMarkers[i].getPosition().lng()));
}
strDefaultLtLong = bound.getCenter();// get center from bounds
}
var image = 'Images/star.png';
var mapOptions = {
center: strDefaultLtLong,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDoubleClickZoom: true,
zoom: parseInt(strDefaultZoomLevel)
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (arrMarkers.length == 1) {
map.setZoom(parseInt(strDefaultZoomLevel));
}
else if (arrMarkers.length > 1) {
map.fitBounds(bound);
google.maps.event.addListener(map, 'idle', function (event) {
if (map.getZoom() > parseInt(strDefaultZoomLevel)) {
map.setZoom(parseInt(strDefaultZoomLevel));
}
});
google.maps.event.clearListeners(map, 'idle');
}
我在arrMarkers中有位置列表。 fitBounds()函数仅在位置具有不同位置但位置列表具有相同位置(Lat&amp; Long)时才有效,然后显示完全缩放的地图。
如何处理默认缩放或特定缩放级别,以便列出适当的显示?
谢谢..
答案 0 :(得分:0)
如果标记的位置真的相等,你可以比较边界的SW和NE,它们也应该相等:
//if (arrMarkers.length == 1) {
if(bounds.getSouthWest().toUrlValue()
===
bounds.getNorthEast().toUrlValue()){
map.setZoom(parseInt(strDefaultZoomLevel));
}
演示:
function init() {
var goo=google.maps,
strDefaultZoomLevel='7',
map = new goo.Map(document.getElementById('map_canvas'),
{
zoom: parseInt(strDefaultZoomLevel),
noClear:true
}),
btn=document.getElementById('btn'),
markers=[
new goo.Marker({position:{lat:11.11,lng:22.22},
icon:{
url:'http://maps.google.com/mapfiles/dir_0.png',
scaledSize:new goo.Size(48,48)
}}),
new goo.Marker({position:{lat:11.11,lng:22.22},
icon:{
url:'http://maps.google.com/mapfiles/dir_60.png',
scaledSize:new goo.Size(48,48)
}}),
new goo.Marker({position:{lat:66.66,lng:77.77},
icon:{
url:'http://maps.google.com/mapfiles/dir_0.png',
scaledSize:new goo.Size(48,48)
}})
];
map.controls[goo.ControlPosition.BOTTOM_CENTER]
.push(btn);
goo.event.addDomListener(btn,'click',function(){
for(var i=0;i<markers.length;++i){
markers[i].setMap(null);
}
this.value=(this.value==='draw equal markers')
? 'draw different markers'
: 'draw equal markers';
var arrMarkers=markers.slice.apply(markers,(this.value==='draw equal markers')
? [1,3]
: [0,2]),
bounds=new goo.LatLngBounds();
for(var i=0;i<arrMarkers.length;++i){
arrMarkers[i].setMap(map);
bounds.extend(arrMarkers[i].getPosition());
}
if(bounds.getSouthWest().toUrlValue()
===
bounds.getNorthEast().toUrlValue()){
map.setOptions({
zoom:parseInt(strDefaultZoomLevel),
center:bounds.getCenter()
});
}
else{
map.fitBounds(bounds);
}
});
google.maps.event.trigger(btn,'click');
}
&#13;
html,body,#map_canvas{height:100%;margin:0;padding:0;}
#btn{font:14px bold Monospace;background:tomato;margin-bottom:12px;}
&#13;
<div id="map_canvas">
<input id="btn" type="button" value="draw equal markers"/>
</div>
<script src="https://maps.googleapis.com/maps/api/js?v=3&callback=init"></script>
&#13;