[英]Using setZoom() after using fitBounds() with Google Maps API V3
我正在使用fitBounds()在我的地圖上設置縮放級別,也包括當前顯示的所有標記。 但是,當我只有一個標記可見時,縮放級別為100%(...我認為縮放級別為20 ......)。 但是,我不希望它被放大,因此用戶可以調整標記的位置而不必縮小。
我有以下代碼:
var marker = this.map.createMarker(view.latlng, this.markerNumber);
this.map.bounds.extend(view.latlng);
this.map.map.setCenter(this.map.bounds.getCenter());
this.map.map.fitBounds(this.map.bounds);
if (this.markerNumber === 1) {
this.map.map.setZoom(16);
}
this.markerNumber++;
其中this.map.bounds先前定義為:
this.map.bounds = new google.maps.LatLngBounds();
但是,我遇到的問題是該行this.map.map.setZoom(16);
如果我使用this.map.map.fitBounds(this.map.bounds);
但是,我知道這行代碼是正確的,因為當我注釋掉fitBound()行時,setZoom()會神奇地開始運行。
我有什么想法解決這個問題? 我正在考慮設置一個maxZoom級別作為替代,如果我不能讓它工作。
好吧,我已經明白了。 顯然,fitbounds()是異步發生的,因此在設置縮放工作之前必須等待bounds_changed
事件。
map = this.map.map;
map.fitBounds(this.map.bounds);
zoomChangeBoundsListener =
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(16);
}
});
setTimeout(function(){google.maps.event.removeListener(zoomChangeBoundsListener)}, 2000);
更新 :使用addListenerOnce
查看@ Nequin的答案,以獲得不需要超時的更好解決方案。
google.maps.event.addListenerOnce(yourMap, 'bounds_changed', function(event) {
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
此解決方案效果更好...而不是等待超時刪除偵聽器。 在使用fitBounds
之前直接調用它(我相信調用后也會起作用)。
我發現額外的變焦有點刺耳。 如果在調用fitBounds之前設置maxZoom選項(然后在回調中取消設置),則可以避免它:
map.setOptions({
maxZoom: 10
});
map.setCenter(new google.maps.LatLng(-89, -179)); // make sure it changes so the idle listener gets called back
map.fitBounds(bounds);
var listener = google.maps.event.addListenerOnce(map, "idle", function()
{
map.setOptions({
maxZoom: 999
});
});
我有簡單而骯臟的解決方案。
使用如果否則......
var marker = this.map.createMarker(view.latlng, this.markerNumber);
this.map.bounds.extend(view.latlng);
this.map.map.setCenter(this.map.bounds.getCenter());
if (this.markerNumber === 1) {
this.map.map.setZoom(16);
} else {
this.map.map.fitBounds(this.map.bounds);
}
this.markerNumber++;
我剛剛在函數addBounds(position)
添加了一行並修復了它,如下所示:
addBounds: function(position) {
this.get('bounds', new google.maps.LatLngBounds()).extend(this._latLng(position));
this.get('map').fitBounds(this.get('bounds'));
this.get('map').setZoom(16);//line added
return this;
},
我認為正確的方法是你需要在map.fitBounds(bounds)
之后設置縮放級別。 只需在map.fitBounds(bounds)
之后添加map.setZoom(16)
map.fitBounds(bounds)
。 這對我來說可以。
所有帶有事件監聽器的解決方案對我都不起作用(this.getZoom()在回調中始終未定義,this.setZoom()無效)。
我提出了這個解決方案很好用:
function set_zoom() {
if(map.getZoom()) {map.setZoom(map.getZoom() - 1);}
else {setTimeout(set_zoom, 5);}
}
setTimeout(set_zoom, 5);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.