2013-05-16 4 views
0

Google지도를 생성하려고하는데 거리 주소를 기반으로 각 표식의 좌표를 찾아야합니다. 좌표는 괜찮지 만, "마지막"입력 된 거리 주소에 대한 좌표 만 제공합니다. 나는 그들 각각을위한 배열이 필요하다.하나의 함수에서 여러 개의 streetaddress에 대한 좌표를 얻습니다.

는 HTML :

<div class="gmapItems"> 
<input type="text" class="input-medium googleMapCity" value='New York'> 
<input type="text" class="input-medium googleMapAddress"> 
<textarea class="input-medium googleMapInformation" value='1'></textarea> 
</div> 

<div class="gmapItems"> 
<input type="text" class="input-medium googleMapCity" value='Boston'> 
<input type="text" class="input-medium googleMapAddress"> 
<textarea class="input-medium googleMapInformation" value='1'></textarea> 
</div> 

JQuery와 :

$("#AddGoogleMap").on('click', function() {    
    mapMarkers = new Array(); 
    $('.gmapItems').each(function(){ 
    gmapInfo = $('.googleMapInformation',this).val();  

    geocoder = new google.maps.Geocoder(); 
    address = $('.googleMapCity',this).val(), $('.googleMapAddress',this).val(); 

    geocoder.geocode({ 'address': address}, function(results, status) { 

      if (status == google.maps.GeocoderStatus.OK) { 
     latitude = results[0].geometry.location.lat(); 
     longitude = results[0].geometry.location.lng(); 
     LatLng = new google.maps.LatLng(latitude , longitude); 
     } 
    }); 

    mapMarkers.push("["+"'"+gmapInfo+"'", latitude, longitude+"]"); 
    }); 
    alert(mapMarkers) 

답변

1

지오 코딩은 비동기입니다. 콜백 루틴 (사용할 수있는 경우) 내부의 데이터를 사용해야합니다. 당신이 합리적인 방식으로 코드를 들여 쓰기를하면 그이고, 당신은 볼 수 있습니다

$("#AddGoogleMap").on('click', function() {    
    mapMarkers = new Array(); 
    $('.gmapItems').each(function(){ 
    gmapInfo = $('.googleMapInformation',this).val();  

    geocoder = new google.maps.Geocoder(); 
    address = $('.googleMapCity',this).val(), $('.googleMapAddress',this).val(); 

    geocoder.geocode({ 'address': address}, function(results, status) { 

    if (status == google.maps.GeocoderStatus.OK) { 
     latitude = results[0].geometry.location.lat(); 
     longitude = results[0].geometry.location.lng(); 
     LatLng = new google.maps.LatLng(latitude , longitude); 
     mapMarkers.push("["+"'"+gmapInfo+"'", latitude, longitude+"]"); 
    } else { 
     alert("Geocoding failed: " + status); 
    } 
    }); 
}); 

귀하의 alert(mapMarkers)는 현재 코드에서 실행 한 후 모든 결과는, 구글의 서버에서 반환 될 때까지 이해가되지 않습니다 .

+0

감사! 잘 작동합니다! 그러나 어떻게 배열에 저장하고 whem을 mapMarkers로 사용할 수 있습니까? – Kim

+0

물론입니다. 그것이 _ 나중에 _ 있고 _ mapMarkers 배열이 여전히 범위 내에있는 한 (아마도 그것이 전역 범위에 있음을 의미합니다). – geocodezip

관련 문제