2011-08-09 50 views
14

我正在使用Google Maps API v3來對地址進行地理編碼。如何將附加信息傳遞給geocodeCallBack函數?看到我的代碼&評論下面瞭解我想要實現的。Google Maps API v3 - 將更多信息傳遞到GeoCode回撥?

var address = new Array(); 
address[0] = {name:'Building 1',address:'1 Smith Street'}; 
address[1] = {name:'Building 2',address:'2 Smith Street'}; 

for(var rownum=0; rownum<=address.length; rownum++) 
{ 
     if(address[rownum]) 
       geocoder.geocode({'address': address[rownum].address}, geocodeCallBack); 
} 

function geocodeCallBack(results, status) 
{ 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location, 
      //how can I also add the name of the building to the title attribute? 
      title: results[0].formatted_address 
     }); 
} 

回答

19

作出關閉的geocodeCallBackmakeCallback。封閉獲取並保持rownum

for (var rownum=0; rownum<=address.length; rownum++) { 
    if (address[rownum]) 
     geocoder.geocode({'address': address[rownum].address}, makeCallback(rownum)); 
} 

function makeCallback(addressIndex) { 
    var geocodeCallBack = function(results, status) { 
     var i = addressIndex; 
     alert(address[i].name + " " + results[0].formatted_address); 
     var marker = new google.maps.Marker({ 
      map: map, 
      position: results[0].geometry.location, 
      // use address[i].name 
      title: results[0].formatted_address 
     }); 
    } 
    return geocodeCallBack; 
} 

當然,你也可以做一個封閉makeCallback(addressName)直接傳授的名字,但上面的版本與地址索引是比較一般。

+0

這裏的closure如何替換geocode函數?我很困惑它是如何工作的 –