【问题标题】:Google Maps API, markers in a for loop and attributes changingGoogle Maps API,for循环中的标记和属性更改
【发布时间】:2017-12-22 15:40:35
【问题描述】:

我遇到了 Google Maps API 标记的问题,

这里是 ajax succes 函数的代码(map 是包含此代码的函数的参数):

success: function(data) {
   var tmpmap = map;                         //Without this the map wont let me add markers
   ris = JSON.parse(data);                   //Parsing to json
   for (var i = 0; i < ris.length - 1; i++) {//Here is the for 
      var id = ris[i].id_sede;               //Here i get the id from the json
      var marker = new google.maps.Marker({  //Here i create the marker
         map: tmpmap,
         mid: id,                            //And there is where i got that problem.
         position: {
         lat: parseFloat(ris[i].latitude),
         lng: parseFloat(ris[i].longitude)
      }
});

ajax 收集的数据是一个普通的 SQL 查询,其中包含纬度、经度、ID 和一些额外的信息。

所以问题是:在for的每个循环中,之前创建的每个标记都假定当前“mid”(地图ID)的值。

TL;DR 我有 4 个标记,在循环结束时,中间 1 2 3 和 4 所有标记的中间值都是 4,而不是 1 2 3 和 4。

最后一个问题是:如何防止这种行为?我是否正确创建标记?为什么当我改变一个标记的值时,所有其他标记都做同样的事情?

【问题讨论】:

    标签: javascript google-maps


    【解决方案1】:

    您必须使用IIFE,以便每个制造商获得自己的数据:

    success: function (data) {
      var tmpmap = map; //Without this the map wont let me add markers
      ris = JSON.parse(data); //Parsing to json
      for (var i = 0; i < ris.length - 1; i++) { //Here is the for 
        // IIFE
        (function (entry) {
          // remember original element as variable entry
          var marker = new google.maps.Marker({ //Here i create the marker
            map: tmpmap,
            mid: entry.id_sede, // still the original ID
            position: {
              lat: parseFloat(entry.latitude),
              lng: parseFloat(entry.longitude)
            }
          });
        }) (ris[i]); // pass original element into IIFEE
      }
    });
    

    因为在第一个标记获得其 ID 之前没有 IIFE,变量 i 可能已经达到条件 ris.length - 1。所以在这种情况下,变量 id 不会包含第一个标记的 ID。

    通过使用 IIFE,您可以使用 ris 中的原始条目元素。

    希望这会有所帮助。

    【讨论】:

    • 感谢您的帮助!
    • 如果能帮您解决所有问题,请标记为正确答案,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-24
    • 2013-05-31
    • 2011-03-14
    • 1970-01-01
    • 2018-04-16
    • 2013-07-20
    • 2013-01-28
    相关资源
    最近更新 更多