简体   繁体   English

调整窗口大小时,使Google地图居中

[英]keep google maps centered when window resize

I am trying to center google maps when window is resized. 调整窗口大小时,我正在尝试使Google地图居中。 I looked around many examples on stackoverflow but nothing of those seems to be working for me. 我查看了许多关于stackoverflow的示例,但这些示例似乎对我没有用。 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. 当您调用map.setCenter(center)center的值已根据地图的新大小进行了更新。

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/ 演示: http : //jsfiddle.net/doktormolle/Xce4w/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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