2013-09-26 74 views
0

我有一个小问题,我有下面的代码,显然一切工作正常,除了标记的标题。它总是显示数组列表的最后一个标题。有人知道为什么这个错误?谷歌地图多个标记

代码:

$(document).ready(function() { 

      var options = { 
       zoom: 7, 
       center: new google.maps.LatLng(42.19708, 2.19075), 
       mapTypeId: google.maps.MapTypeId.ROADMAP, 
       mapTypeControl: true 
      }; 

      var geocoder = new google.maps.Geocoder(); 
      var map = new google.maps.Map(document.getElementById('map_canvas'), options); 

      var companys = [ 
       ['Giga S.L', 'Plaça de Catalunya, Barcelona'], 
       ['Torre M', 'Plaça d\'Espanya, Barcelona'] 
      ]; 

      var address; 
      var title; 

      for (var i = 0; i < companys.length; i++) { 
       address = companys[i][1]; 
       title = companys[i][0]; 

       geocoder.geocode({'address': address}, function(results, status) { 
        if (status === google.maps.GeocoderStatus.OK) { 
         map.setCenter(results[0].geometry.location); 

         new google.maps.Marker({ 
          map: map, 
          animation: google.maps.Animation.DROP, 
          position: results[0].geometry.location, 
          title: title // ERROR: ALWAYS THE SAME TITLE 
         }); 
        } else { 
         alert('Geocode was not successful for the following reason: ' + status); 
        } 
       }); 
      } 
     }); 

预先感谢您。

此致敬礼。

回答

1

一个解决这种方式来包装调用geocodeimmediately-invoked function expression(IFFE),在您的变量传递的参数:

(function(address, title) { // the variables are passed in here as function parameters 

    geocoder.geocode({'address': address}, function(results, status) { 
    if (status === google.maps.GeocoderStatus.OK) { 
     map.setCenter(results[0].geometry.location); 

     new google.maps.Marker({ 
     map: map, 
     animation: google.maps.Animation.DROP, 
     position: results[0].geometry.location, 
     title: title 
     }); 
    } else { 
     alert('Geocode was not successful for the following reason: ' + status); 
    } 
    }); 

}(address, title)); // pass in address/title into the IFFE 
+0

非常感谢,完美的作品! –

1

geocoder.geocode有一个回调函数。这意味着代码异步运行。您将不得不重构您的代码以从回调中检索公司头衔。

在您的代码中,返回geocode回调之前,for循环已经完成,这就是为什么您的变量标题设置为最后一个。

+0

非常感谢您! –