【问题标题】:keep google maps centered when window resize调整窗口大小时保持谷歌地图居中
【发布时间】:2014-05-30 05:50:17
【问题描述】:

我试图在调整窗口大小时将谷歌地图居中。我查看了有关 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);
});

我在地图上也有标记,当地图位于中心位置时,它们也应该相应地适合。我在这里错过了什么吗?

【问题讨论】:

  • 您的代码中没有任何内容可以使地图适合标记。为此,您需要将它们添加到 google.maps.LatLngBounds 对象并调用 map.fitBounds 而不是 map.setCenter。
  • 没关系。我有单独的代码来做到这一点。但我的主要问题是为什么我的地图在调整窗口大小时没有居中?
  • 无法从您发布的代码中分辨出来。请提供一个 Minimal, Complete, Tested and Readable example 来证明该问题。

标签: javascript google-maps google-maps-api-3 maps


【解决方案1】:

当你调整窗口(和地图)的大小时,地图的中心也会改变(当你没有触发调整大小事件时)。

当您调用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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 1970-01-01
    • 2011-04-05
    • 2019-10-05
    相关资源
    最近更新 更多