谷歌地图异步添加标记

Google Maps Asynchronously Add Markers

本文关键字:加标记 添加 异步 谷歌地图      更新时间:2023-09-26

我正在玩谷歌地图API,想加载一张地图,然后使用边界访问外部API,以获取地图中多个城市的当前天气状况。我遇到的问题是,如果我有async: false,它可以正常工作,但一旦我设置了async: true,标记就不再加载。这就是我所拥有的,我觉得这是一件非常简单的事情。

function initialize()
{
  var mapProp = {
    center: new google.maps.LatLng(41.8369,-95.6847),
    zoom:4,
    disableDefaultUI:true,
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };
  map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
  google.maps.event.addListener(map, 'bounds_changed', function() {
      calcBounds();
  });
function calcBounds() {
  var bounds = map.getBounds();
  var ne = bounds.getNorthEast();
  var sw = bounds.getSouthWest();
  for (var lat = ne.lat(); lat > sw.lat(); lat = lat - 5) {
    for (var long = ne.lng(); long > sw.lng(); long = long - 5) {
      $.ajax({
        async: false,
        url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + long + '&APPID=' + apikey,
        dataType: "json",
        success: function(data) {
          var marker = new google.maps.Marker({
            map: map,
            position: new google.maps.LatLng(lat, long),
          });//End Marker
        },//End Success
        error: function() {
         alert("ERROR");
        }
      });//End AJAX
    }//End Long for
  }//End lat For
}//End function

对于学习Javascript的人来说,您遇到的问题很常见。发生的事情是,每次你经过循环的一次迭代,lat&long被更改。这就成了一个问题,因为您的ajax函数正在引用这个变量!因此,在实践中,这意味着所有的web请求都将针对相同的lat和long,因为循环可能在第一个ajax请求发送之前就已经完成了。。。执行其中一个循环大约需要5毫秒,发送和接收ajax请求大约需要50-100毫秒。将其设置为async:false有效(但它会冻结浏览器!),因为它会等到发送并返回请求后再更改latlong变量的值。因此,很明显,您希望ajax请求记住您希望它查找的值,而不是现在的内存值。解决方案是将要使用的变量放在闭包中,这样它们就可以保留在ajax函数的本地,并且在循环的下一次迭代中不会发生更改。

下面是一个工作示例。和一个jsfiddle:http://jsfiddle.net/47b3mjn3/2/

  function initialize() {
    var mapProp = {
        center: new google.maps.LatLng(41.8369, -95.6847),
        zoom: 4,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.SATELLITE
    };
    map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
    google.maps.event.addListener(map, 'bounds_changed', function () {
        calcBounds();
    });
    function calcBounds() {
        var bounds = map.getBounds();
        var ne = bounds.getNorthEast();
        var sw = bounds.getSouthWest();
        for (var lat = ne.lat(); lat > sw.lat(); lat = lat - 5) {
            for (var long = ne.lng(); long > sw.lng(); long = long - 5) {
                addMarker(lat, long);
            } //End Long for
        } //End lat For
    } //End function
}
function addMarker(lat, long) {
    _lat = lat;
    _long = long;
    $.ajax({
                    url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + _lat + '&lon=' + _long + '&APPID=' + apiKey,
                    dataType: "json",
                    success: function (data) {
                        new google.maps.Marker({
                            map: map,
                            position: new google.maps.LatLng(_lat, _long),
                        }); //End Marker
                    }, //End Success
                    error: function () {
                        alert("ERROR");
                    }
                }); //End AJAX
}
initialize();