简体   繁体   English

Google Maps异步添加标记

[英]Google Maps Asynchronously Add Markers

I am playing around with the Google Maps API and want to load a map, then use the bounds to hit an external API to get current weather conditions for a number of cities in the map. 我正在使用Google Maps API,并希望加载地图,然后使用边界点击外部API以获取地图中许多城市的当前天气状况。 The problem I am running into is that if I have async: false it works fine, but once I set async: true the markers no longer load. 我遇到的问题是,如果我有async: false它可以正常工作,但是一旦我设置了async: true ,标记就不再加载。 Here's what I have, I get the feeling it's something really simple. 这就是我所拥有的,我感觉这很简单。

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

The problem you have is a common one for people learning Javascript. 对于学习Javascript的人来说,您遇到的问题是一个普遍的问题。 What is happening is that every time you go through one iteration of the loop the value of lat & long is changed. 发生的情况是,每次循环迭代一次,lat&long的值都会更改。 This becomes a problem because your ajax functions are referencing this variable! 因为您的ajax函数正在引用此变量,所以这将成为一个问题! So, in practice this means that all of your web requests will be for the same lat and long because the loop has likely already finished before the first ajax request has even been sent... It takes about 5ms to do one of these loops and closer to 50-100ms to send and receive an ajax request. 因此,实际上这意味着您的所有Web请求都将使用相同的经度和时间,因为循环可能甚至在发送第一个ajax请求之前就已经完成了……大约需要5毫秒才能完成这些循环之一,接近50-100毫秒以发送和接收ajax请求。 Setting it to async: false works (but it freezes the browser!) because it waits until the request has been sent and returned before changing the value of the lat and long variables. 将其设置为异步:false可以工作(但会冻结浏览器!),因为它在更改latlong变量的值之前一直等到请求已发送并返回。 So, clearly you want the ajax request to remember the value you want it to look up and not the value that is memory right now. 因此,很明显,您希望ajax请求记住要查找的值,而不是现在的内存值。 The solution is to put the variables you are going to use in a closure, so that they stay local to ajax function and don't get changed on the next iteration of the loop. 解决方案是将要使用的变量放在闭包中,以便它们在ajax函数中保持局部状态,并且在循环的下一次迭代中不会更改。

Here is a working example. 这是一个工作示例。 and a jsfiddle: http://jsfiddle.net/47b3mjn3/2/ 和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();

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

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