2017-01-25 1 views
-1

나는 JS에 비교적 익숙하다고 말하기 시작합니다.이 점이 분명한 경우 내 용서를 용서하십시오.Google지도 api 및 지오 코딩 API - 마커 추가 문제

마커를 Google지도에 추가하려고합니다. 배열 coordList를 만든 다음 지오 코딩 API를 사용하여 주소에서 long 및 long을 가져 와서 coordList로 푸시했습니다.

이제 coordList 배열을 사용하여 맵에 마커를 플롯하려고했지만 coordList 배열에서 값을 가져올 수 없습니다. console.log (typeof coordList)를 실행하면 객체라고 알려주지 만, console.log (coordList)로 배열을 보면 일반 배열처럼 보입니다. coordList가 비어 있도록

var coordList = []; 
    var address = []; 

address.push('52+Kalynda+pde,+bohle+plains,+QLD') 
address.push('51+Frank+St,+Kirwan+QLD+4817'); 

    function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 12, 
     center: new google.maps.LatLng(-19.259854,146.8001348), 
     mapTypeId: 'roadmap' 
    }); 


    } 

    function getLatLong(address){ 
    var index; 
    for (index = 0; index < address.length; ++index) { 

    var request = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address[index] + '&key=[MY_key]'; 

    $.getJSON(request, function(data) { 

    var lat = data.results[0].geometry.location.lat; 
    var lng = data.results[0].geometry.location.lng; 

     var coords = []; 
     coords.push(lat); 
     coords.push(lng); 
     //push coords into coordList 
     coordList.push(coords); 

    }); 
    } 
    } 


    // Loop through the results array and place a marker for each 
    // set of coordinates. 
    function addMarkers(coordList) { 

    for (var i = 0; i < coordList.length; i++) { 

     var coords = coordList[i]; 
     var latLng = new google.maps.LatLng(coords[0],coords[1]); 
     var marker = new google.maps.Marker({ 
     position: latLng, 
     map: map 
     }); 
    } 
    } 
    getLatLong(address); 
    addMarkers(coordList); 

답변

1

귀하의 문제는() 완료 $ .getJSON()는 비동기 요청하고 코드가 $ .getJSON 이상 전) (addMarkers를 실행하는 것입니다.

$ .getJSON() 콜백 내에 마커를 추가 할 수 있습니다. 예를 들면 다음과 같습니다.

var address = []; 

address.push('52+Kalynda+pde,+bohle+plains,+QLD') 
address.push('51+Frank+St,+Kirwan+QLD+4817'); 

function initMap() { 
    map = new google.maps.Map(document.getElementById('map'), { 
     zoom: 12, 
     center: new google.maps.LatLng(-19.259854,146.8001348), 
     mapTypeId: 'roadmap' 
    }); 
} 

function getLatLongAndAddMarkers(address){ 
    var index; 
    for (index = 0; index < address.length; ++index) { 
    var request = 'https://maps.googleapis.com/maps/api/geocode/json?dress=' + address[index] + '&key=[MY_key]'; 
    $.getJSON(request, function(data) { 
     var latLong = new google.maps.LatLng(data.results[0].geometry.location); 
     //add markers here 
     var marker = new google.maps.Marker({ 
      position: latLong, 
      map: map 
     }); 
    }); 
    } 
} 

getLatLongAndAddMarkers(address); 
+0

고맙습니다. 이제 내 머리를 들었습니다. – DGBatch