Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

javascript - Using setZoom() after using fitBounds() with Google Maps API V3

I'm using fitBounds() to set the zoom level on my map too include all the markers currently displayed. However, when I have only one marker visible, the zoom level is 100% (... which zoom level 20 I think...). However, I don't want it to be that far zoomed in so the user can adjust the position of the marker without having to zoom out.

I have the following code:

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++;

where this.map.bounds was previously defined as:

this.map.bounds = new google.maps.LatLngBounds();

However, the problem I am having is that the line this.map.map.setZoom(16); doesn't work if I use this.map.map.fitBounds(this.map.bounds);, however, I know that line of code is correct because when I comment out the fitBound() line, the setZoom() magically starts functioning.

Any ideas how I resolve this? I'm thinking of setting a maxZoom level as an alternative if I can't get this working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Alright, I've figured it out. Apparently, the fitbounds() happens asynchronously, so you have to wait for a bounds_changed event before setting zoom works.

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);

Update: See @Nequin's answer using addListenerOnce for a better solution that doesn't require a timeout.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...