当使用Geocoder()时,MarkerWithLabel仅显示google地图api中的最后一个值

MarkerWithLabel show only last value in the google map api when using Geocoder()

本文关键字:地图 google 显示 api 最后一个 MarkerWithLabel Geocoder      更新时间:2023-09-26

当我用MarkerWithLabel添加标记时,它显示了不同的标记,但与之关联的值包含数据的最后一个值。就像在每个标记中,当编写代码labelContent:building.valuetitle:building.Country_Name时,它显示每个制造商位置的最后一个国家名称,如尼泊尔,它显示来自数据的最后一个值,如…63在这种情况下。我有以下JSON格式的数据。

       var recipient_country = [{"Country_Name": "MYANMAR", "value": 123},
       {"Country_Name": "MONGOLIA", "value": 11},
       {"Country_Name": "ZIMBABWE", "value": 22},
       {"Country_Name": "Bahrain", "value": 45},
       {"Country_Name": "Nepal", "value": 63}];

  for(var i= 0; i < recipient_country.length; i++) {
        console.log(i);
        var building = recipient_country[i];
        console.log(building.Country_Name);
        geocoder.geocode({'address':building.Country_Name}, function(results,status){
          console.log(results);
          if(status == google.maps.GeocoderStatus.OK){
            var marker = new MarkerWithLabel({
              position:results[0].geometry.location,
              title:building.Country_Name,
              map:map,
              labelContent:building.value,
              labelAnchor:new google.maps.Point(6,22),
              labelClass:"labels",
              labelInBackground:false,
              icon:"circle2.png"
            });
             console.log(building.Country_Name)
          }
          else{
                 console.log("Geocode was not  succcessful for the following reason:" + status);
             }
        });
      

geocoder.geocode()函数是异步的,因为在for循环中没有特殊的作用域,所以building变量在每次迭代时被覆盖,使您在稍后执行geocode()函数时得到迭代的最后一个值。

你必须用一个新的作用域锁定这个值:

for (var j = 0; j < recipient_country.length; j++) {
    (function(i) {
        var building = recipient_country[i];
        geocoder.geocode({
            'address': building.Country_Name
        }, function (results, status) {
            console.log(results);
            if (status == google.maps.GeocoderStatus.OK) {
                var marker = new MarkerWithLabel({
                    position: results[0].geometry.location,
                    title: building.Country_Name,
                    map: map,
                    labelContent: building.value,
                    labelAnchor: new google.maps.Point(6, 22),
                    labelClass: "labels",
                    labelInBackground: false,
                    icon: "circle2.png"
                });
                console.log(building.Country_Name)
            } else {
                console.log("Geocode was not  succcessful for the following reason:" + status);
            }
        });
    })(j);
}