-1

我想要一個名爲「標記」的數組的JavaScript數組存儲的名稱和街道地址,我想添加爲一個谷歌地圖上的標記。使用索引通過谷歌地圖地理代碼循環API

var markers = [['Name of Place', '123 1st Street New York, NY'], ['Place 2', '122 1st Street, New York, NY']]; 

我沒有問題,使地圖顯示正常,甚至使標記出現與從「標記」數組訪問的標題。只要我明確地從「標記」數組訪問標題。如下圖所示:

var map; 
var geocoder; 

    function initMap(){ 
      map = new google.maps.Map(document.getElementById('map'), { 
        center: {lat: 34.6760942, lng: -82.8386035}, 
        zoom: 13 
      }); 

      geocoder = new google.maps.Geocoder(); 

      for(i = 0; i < markers.length; i++){ 
       geocoder.geocode({'address': markers[i][1]}, function(results, status) { 
        if(status == 'OK'){ 
         marker = new google.maps.Marker({ 
           map: map, 
           position: results[0].geometry.location, 
           title: markers[0][0] 
         }); 
        } else { 
         alert('Geocode was not successful because: ' + status); 
        } 
       }); 
      } 
    } 

不過,我希望能夠使用該索引,「我」,在for循環反覆創建這些標記。如果我嘗試使用(title:markers [i] [0])從「markers」數組中迭代獲取標題,如下所示。我得到一個「未捕獲的類型錯誤:無法讀取屬性‘0’的未定義

VAR地圖; VAR地理編碼;

function initMap(){ 
     map = new google.maps.Map(document.getElementById('map'), { 
       center: {lat: 34.6760942, lng: -82.8386035}, 
       zoom: 13 
     }); 

     geocoder = new google.maps.Geocoder(); 

     for(i = 0; i < markers.length; i++){ 
      geocoder.geocode({'address': markers[i][1]}, function(results, status) { 
       if(status == 'OK'){ 
        marker = new google.maps.Marker({ 
          map: map, 
          position: results[0].geometry.location, 
          title: markers[i][0] 
        }); 
       } else { 
        alert('Geocode was not successful because: ' + status); 
       } 
      }); 
     } 
} 

出於某種原因,在函數索引,我,沒有定義。我該如何去確保「i」被定義在函數內部?

回答

2

我建議你使用封閉?

function geocodeEncapsulation(i) { 
    return(function(results, status){ 
     if(status == 'OK'){ 
        marker = new google.maps.Marker({ 
          map: map, 
          position: results[0].geometry.location, 
          title: markers[i][0] 
        }); 
       } else { 
        alert('Geocode was not successful because: ' + status); 
       } 
    }); 
} 

function initMap(){ 
     map = new google.maps.Map(document.getElementById('map'), { 
       center: {lat: 34.6760942, lng: -82.8386035}, 
       zoom: 13 
     }); 

     geocoder = new google.maps.Geocoder(); 

     for(i = 0; i < markers.length; i++){ 
      geocoder.geocode({'address': markers[i][1]}, geocodeEncapsulation(i)); 
     } 
} 
+0

感謝您的幫助,我試圖做類似的東西我自己earli呃,但似乎無法使其正確工作。儘管如此,我仍然會努力工作,所以我會回頭看看我出錯的地方。 –

+0

不客氣。我很高興我的回答對你有幫助;) –