2012-09-09 79 views
1

代碼:如何將對象傳遞給這個js函數?

function setMaps() { 
    var geocoder = new google.maps.Geocoder(); 
    var result = ""; 

    $('.map_canvas').each(function(){ 

     geocoder.geocode({ 
      'address': $(this).attr('address'), 
      'region': 'de' 
     }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       result += results[0].geometry.location.lng()+","; 
       result += results[0].geometry.location.lat(); 
      } else { 
       result = "Unable to find address: " + status; 
      } 
      $(this).gmap({ 'center': result }); 
     }); 
    }); 
} 

這種方法應該表現出一個頁面上的多個地圖。

HTML:

<div class="map_canvas" address="Berlin, Zoo"> 

</div> 

問題是$(this).gmap({ 'center': result });不起作用:

Uncaught TypeError: Cannot set property 'position' of undefined 

任何想法如何將map_canvas提供對象傳遞給回調函數?

回答

2

試試這個:

function setMaps() { 
    var geocoder = new google.maps.Geocoder(); 
    var result = ""; 

    $('.map_canvas').each(function(){ 
     var _this = $(this); // <------ here 
     geocoder.geocode({ 
      'address': $(this).attr('address'), 
      'region': 'de' 
     }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       result += results[0].geometry.location.lng()+","; 
       result += results[0].geometry.location.lat(); 
      } else { 
       result = "Unable to find address: " + status; 
      } 
      _this.gmap({ 'center': result }); // <---- and here 
     }); 
    }); 
} 
相關問題