简体   繁体   中英

keep google maps centered when window resize

I am trying to center google maps when window is resized. I looked around many examples on stackoverflow but nothing of those seems to be working for me. Here's sample code:

google.maps.event.addDomListener(window, 'resize', function() {
  //Window Resize and Position map to center
  center = map.getCenter();
  google.maps.event.trigger(map, 'resize');
  map.setCenter(center);
});

I have markers also on the map which should also fit accordingly when map is center positioned. Am I missing something here ?

when you resize the window(and the map), the center of the map changes too(also when you didn't trigger the resize-event).

When you call map.setCenter(center) the value of center already has been updated regarding to the new size of the map.

You must store the center of the map each time when it changes(except when the map has been resized), and when the map has been resized restore the stored value.

Possible solution:

  google.maps.event.addListener(map, 'center_changed', function() {

    //a value to determine whether the map has been resized
    var size=[this.getDiv().offsetWidth,this.getDiv().offsetHeight].join('x');

    //when the center has changed, but not the size of the map
    if(!this.get('size') || size===this.get('size')){
       this.setValues({size:size,_center:this.getCenter()});         
    }
    //when the map has been resized
    else{
      google.maps.event.addListenerOnce(this,'idle',function(){
      this.setValues({size:size,center:this.get('_center')});});      
    }
  });
  //trigger the resize-event to initialize the size and _center-values
  google.maps.event.trigger(map,'center_changed',{});

Demo: http://jsfiddle.net/doktormolle/Xce4w/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM