2011-08-15 13 views
2

運転/歩行期間に基づいてGoogleマップの住所を除外しようとしています。 私はこのJavaScriptスニペットの実行方法には本当に基本的な何かが欠けているようしかし、それはそう:Googleマップの運転場所に基づいて住所をフィルタリングする

//addresses that I'd like to compare to a point of origin 
var addresses = ['address_1','address_2','address_3','address_4','address_5']; 
//point of interest/origin 
var origin = 'origin_address'; 

for (i=0;i<addresses.length;i++){ 
    var directionsService = new google.maps.DirectionsService(); 
    var directionsDisplay = new google.maps.DirectionsRenderer(); 
    directionsDisplay.setMap(map); 

    var request = { 
    origin: origin, 
    destination: addresses[i], 
    travelMode: google.maps.DirectionsTravelMode.DRIVING 
    }; 

    directionsService.route(request, function(response, status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
     //====> Why can't I access results[i] here? I get "undefined" for the following 
     alert(addresses[i]); 

     // I get 3 identical values, then a unique fourth value 
     alert(response.routes[0].legs[0].duration.value); 

     //if the duration is below a certain value, I'd like to show a marker. 
     //however, I can't do that, since I can't access addresses[i] 
     if(response.routes[0].legs[0].duration.value < 1200){ 
     //Geocode address & show marker 
     } 
    } 
    }); 
} 

理由を任意のアイデア:私は内側から変数「アドレス」にアクセスすることはできません 1):directionsService.routeを(要求、機能(応答、ステータス){ // .....ここ..... ..... });

2)これは、異なるルートの所要時間を比較する正しい方法ですか、それとも真剣に非効率的なことをしていますか?

ありがとうございます!

答えて

2

この関数はコールバック関数です。その範囲は異なっている。あなたはそれが何であると思いますか?その機能では、私は存在しません。

私の電話は本当に悪いですが、あなたの応答変数には、あなたが探している変数からの変数が要求されます。

EDIT

あなたが試すことができ、クロージャ:

directionsService.route(request, (function (address) { 
    return function(response, status) { 
    if (status == google.maps.DirectionsStatus.OK) { 
     //====> Why can't I access results[i] here? I get "undefined" for the following 
     alert(address); 

     // I get 3 identical values, then a unique fourth value 
     alert(response.routes[0].legs[0].duration.value); 

     //if the duration is below a certain value, I'd like to show a marker. 
     //however, I can't do that, since I can't access addresses[i] 
     if(response.routes[0].legs[0].duration.value < 1200){ 
     //Geocode address & show marker 
     } 
    })(addresses[i]) 
    }); 
+0

おかげミル!それは働いた:) – yasser

関連する問題