-1

Google지도에 마커로 추가하려는 장소의 이름과 주소를 저장하는 "마커"라는 배열의 자바 스크립트 배열을 사용하려고합니다.색인 Google지도 지오 코드 API를 사용하여

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

지도를 제대로 표시하는 데 아무런 문제가 없으며, 마커를 "마커"배열에서 액세스 한 제목으로 표시하는 데 아무런 문제가 없습니다. "marker"배열에서 명시 적으로 제목에 액세스하는 한. 아래와 같이 :

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 루프에서, 인덱스, "I"를 사용할 수 있어야합니다. 아래에 표시된대로 제목 (markers [i] [0])을 사용하여 반복적으로 "마커"배열에서 제목을 잡으려고합니다. 나는 "catch되지 않은 유형의 오류가 발생합니다 : 속성을 읽을 수 없습니다 '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); 
       } 
      }); 
     } 
} 

를, 인덱스가, 내가, 정의되지 않은 함수. . 나는 확실히 만드는 방법에 대한 갈 수있는 방법 "내가"함수 내에서 정의된다?

답변

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

당신은 반갑습니다. 내 대답이 너를 도왔 기 때문에 기쁘다;) –