【问题标题】:maps.getBounds() null when calling on map idle在地图空闲时调用 maps.getBounds() null
【发布时间】:2015-05-19 20:38:00
【问题描述】:

我需要设置指向地图的指针 a) 初始化地图时和 b) 移动地图时。 为了获得标记,我像这样调用我的 API:

var bounds = map.getBounds();

然后获取边界以获得正确的标记。

问题是,当我将 API 调用放入其中时

google.maps.event.addListener(map, "bounds_changed", function(){})

在拖动地图时它被调用的频率太高了,但是如果我使用

google.maps.event.addListener(map, "idle", function(){})

map.getBounds 在初始化时为空。

编辑:更多代码

$(document).ready(function(){    initialize(); });

function initialize() {    mapOptions = {
      zoom : 13,
      minZoom : minimumZoomLevel,
      scrollwheel : false,
      panControl : false    };    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

   google.maps.event.addListener(map, "idle", function() {
      myfunction();    }); });

function myfunction(){    var bounds = map.getBounds(); }

bounds 为空!

【问题讨论】:

  • 你能显示一些代码吗?也许在 jsffidle 中?
  • bounds_changed 事件呢? stackoverflow.com/questions/2832636/…
  • 我在原始帖子中对此发表了评论,拖动时触发太频繁(更好:拖动时!)
  • 我在这里做了这个小提琴:jsfiddle.net/pjhk3Lm9 它工作正常。 map 是否定义为全局变量?在 myFunction() 范围内是否可以访问?

标签: javascript google-maps


【解决方案1】:

我在这里使用这段代码:http://boascervejas.com.br,它工作正常:

var mapgoogle = null;
//do some stuff
var mapOptions = //something here
mapgoogle = new google.maps.Map(document.getElementById("map"), mapOptions);

google.maps.event.addListener(mapgoogle, 'idle', function() {
   var bounds = mapgoogle.getBounds();
   console.log(bounds);
   //it's only called when the "end of the drag" is fired
});

编辑:使用 jsfiddle (http://jsfiddle.net/pjhk3Lm9/) 的完整工作示例:

js:

var map = null;

function initialize(lat, lng) {
   var myLatlng = new google.maps.LatLng(lat,lng);
   var mapOptions = {
      mapTypeControl: false,
      streetViewControl: false,
      center: myLatlng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };

    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    google.maps.event.addListener(map, 'idle', function() {
        console.log(map.getBounds());  
    })
};


navigator.geolocation.getCurrentPosition(
    function(position) {
        initialize(position.coords.latitude, position.coords.longitude);
    },
    function(position) {
        initialize(-23.5354986,-46.6839113);
    }
);

//html and css
<div id="map-canvas"></div>
#map-canvas {
    width: 400px;
    height: 400px;
    border:1px solid #FF0000;
}

【讨论】:

  • 我使用相同的,除了我调用我的函数来获取空闲函数中的标记!?
  • 顺便说一句,您代码中的注释不正确 - 地图空闲时触发一次“空闲”,而不是拖动后触发
  • @RaphaelJeger 这就是我把它放在引号内的原因 ;-)
  • 当然 :) 只是想添加它以避免其他人混淆
  • 谢谢你的小提琴!我现在已经看到 initialize 被触发了两次,第一次 bounds 为 null...
猜你喜欢
  • 1970-01-01
  • 2016-10-05
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多