繁体   English   中英

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

[英]keep google maps centered when window resize

调整窗口大小时,我正在尝试使Google地图居中。 我查看了许多关于stackoverflow的示例,但这些示例似乎对我没有用。 这是示例代码:

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

我在地图上也有标记,当地图居中放置时,标记也应相应地适合。 我在这里想念什么吗?

当您调整窗口(和地图)的大小时,地图的中心也会改变(同样在您未触发调整大小事件的情况下)。

当您调用map.setCenter(center)center的值已根据地图的新大小进行了更新。

每次更改地图时,都必须存储地图的中心(调整地图大小时除外);调整地图大小后,还必须恢复存储的值。

可能的解决方案:

  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',{});

演示: http : //jsfiddle.net/doktormolle/Xce4w/

暂无
暂无

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

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