Google Map上的多个标记:仅显示最后一个标记

问题描述:

我在我的地图上显示多个标记时出现问题。代码首先循环访问数组,然后在显示标记并将infoWindow的内容设置为返回地址之前,反转对lat,lon值的地理编码。Google Map上的多个标记:仅显示最后一个标记

我的代码如下。

for(var i=0; i < useNowArray.length; i++) { 
     // plot useNow on map 
     latlng = new google.maps.LatLng(useNowArray[i]['lat'], useNowArray[i]['lon']); 
     console.log(useNowArray[i]['lat'] + useNowArray[i]['lon']); 
     geocoder.geocode({'latLng': latlng}, function(results, status) 
     { 
      if (status == google.maps.GeocoderStatus.OK) 
      { 
       if (results[0]) 
       { 
        marker = new google.maps.Marker({ 
         position: latlng, 
         map: map, 
         icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png', 
         title: results[0].formatted_address 
        }); 
        content = results[0].formatted_address; 
        console.log(content); 

        google.maps.event.addListener(marker, 'click', (function(marker, i) { 
         return function() { 
          infowindow.setContent(content); 
          infowindow.open(map, this); 
         } 
        })(marker, i)); 
       } 
      } else { 
       alert("Geocoder failed due to: " + status); 
      } 
     }); // end geocode function 
    } 
    var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); 

问题是只显示我的最后一个标记。

我在想什么? :(

千恩万谢。

你的标志变量全球,地理编码是异步的。循环执行,发射了useNowArray.length请求,每一个更新与得到的位置。全球标记时循环完成,该标记在循环的最后位置留下类似问题,与该问题的解决方案:

+0

事实上,他正在使用此代码:http://www.svennerberg.com/2012/03/adding-multiple-markers-to-google-maps-from-json/,但它是极其糟糕的例子,即它不能工作你提到的原因。我也想知道这个人如何写一本书并找到一个出版商。 – Bytemain

+0

该[页面]上的演示(http://www.svennerberg.com/2012/03/adding-multiple-markers-to-google-maps-from-json/)没有此问题,也没有使用地理编码器。 – geocodezip

+0

感谢您的回应! 只改变我的标记变量为本地不能解决问题的权利?我做到了这一点,并试图比较address_count和我的数组长度,就像fitBounds示例中的一样,但它对我也不起作用。 help T_T – chongzixin