javascript - 在 map 空闲时调用maps.getBounds() null

标签 javascript google-maps

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

var bounds = map.getBounds();

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

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

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

拖动 map 时它被频繁调用,但如果我使用

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

边界为空!

最佳答案

我在这里使用这段代码: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;
}

关于javascript - 在 map 空闲时调用maps.getBounds() null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29098720/

相关文章:

google-maps - Google Map成为Illustrator SVG

javascript - 来自不同按钮的 jQuery 切换

javascript - Chart.js 标签中的 HTML

ios - 如何从 iOS 上的 google mp 集群获取对象/位置?

javascript - 有没有办法查看两个 "references"是否引用 Google Places API 中的同一地点?

html - 将文本标签绑定(bind)到输入字段,以便在 Google map 移动它们时它们一起移动

javascript - 更改 jquery 选择范围

javascript - createReadStream 管道在 Electron 1.6 中不起作用

javascript - 如何在mvc4中将多个参数从 View 发送到api Controller

javascript - 使 $.getJSON 立即可用 与 for 的区别