2011-04-12 4 views
1

사용자가 주소를 입력하는 웹 사이트의 경우 사용자가 주문한 물건을 수령 할 수있는 곳에서 가장 가까운 위치를 찾으려고합니다.운전 거리 계산 Google지도 API

사용자 주소에 따라 가능한 픽업 위치를 2와 5 사이로 좁힐 수 있습니다. 따라서 사용자 주소 (지점 A)와 가능한 픽업 위치 사이의 거리를 계산하고 싶습니다.

데모 here은 두 개의 주소로 잘 작동합니다. 필자는 두 개 이상의 주소로 작업 할 수있는만큼 코드를 수정했습니다. 나는 제대로 JS에서 그것을 포맷 할 수없는 것 때문에 내 JS 코드 here 게시했습니다.

코드에는 두 가지 경고가 있습니다. 첫 번째 경고에는 다른 픽업 위치가 올바르게 표시됩니다. 그러나 두 번째 경고에는 항상 LAST 픽업 위치가 표시됩니다.

이유를 설명 할 수 있습니까?


HTML :

<p id="hello">Hello World</p> 

자바 스크립트 : 루프 내부

var geocoder, location1, location2, gDir; 

function initialize(counter) {  
    if(counter == 0){ 
     geocoder = new GClientGeocoder(); 
     gDir = new GDirections(); 
    } 
    GEvent.addListener(gDir, "load", function() { 
     var drivingDistanceMiles = gDir.getDistance().meters/1609.344; 
     var drivingDistanceKilometers = gDir.getDistance().meters/1000; 
     $("#results").append('<strong>Driving Distance: </strong>' + drivingDistanceKilometers + ' kilometers<br /><br />');   
    }); 
} 

function getDistance(agency_add, counter) { 
    initialize(counter); 
    geocoder.getLocations(agency_add, function (response) {  
     if (!response || response.Status.code != 200) { 
      alert("Sorry, we were unable to geocode the address" + agency_add); 
     } 
     else { 
      location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; 
      //alert("ONE: "+location1.address); 
      geocoder.getLocations(document.forms[0].address1.value, function (response) { 
       //alert("TWO: "+location1.address); 
       if (!response || response.Status.code != 200) {alert("Sorry, we were unable to geocode the second address");} 
       else {       
        location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};      
        gDir.load('from: ' + location1.address + ' to: ' + location2.address); 
       } 
      }); 
     } 
    }); 
} 


$(document).ready(function(){ 
    //put each agency address in an array 
    var agencies = [];  
    $(".agency_field").each(function(index) { 
     agencies.push($(this).val()); 
    }); 

    for (var i = 0; i < agencies.length; i++){ 
     var res = getDistance(agencies[i], i); 
    }  
}); 

답변

2

당신이 호출 geocoder.getLocations. geocoder.getLocations는 비동기 적으로 실행됩니다. 첫 번째 요청을 처리하는 동안 두 번째 요청을 받으면 첫 번째 요청을 취소합니다.

다중 스레드 geocoder.getLocations를 사용하려면 여러 인스턴스를 만들어야합니다.

+0

그게 내가 필요한 모든 정보입니다, 이것을 명확히 해 주셔서 감사합니다! – stef

관련 문제