0

私はグーグルマップAPIを使用して2点間の距離を取得しようとします、

function load_points(){
        var geocoder = new GClientGeocoder();

        var firstZip, secondZip;
        geocoder.getLatLng(document.getElementById("firstZip").value, function(point) { 
         if (!point) { 
            alert("This point could not be geocoded"); 
           } else { 
            firstZip = point;
            var marker = new GMarker(point);
            map.addOverlay(marker);
           }
        });

        geocoder.getLatLng(document.getElementById("secondZip").value, function(point) { 
         if (!point) { 
            alert("This point could not be geocoded"); 
           } else { 
             secondZip = point;
             var marker = new GMarker(point);            
             map.addOverlay(marker);
            }
        });

        alert(new GLatLng(firstZip).distanceFrom(new GLatLng(secondZip)));

    }

問題は、最初にアラートが実行され、その後ジオコーディング部分が実行されたように見えることです。もちろん、firstZipとsecondZipの値が定義されていないため、distanceFromメソッドは失敗します。誰かがそれを解決する方法を知っていますか?

4

1 に答える 1

1

getLatLng関数は非同期であるため、firstZipandsecondZip変数を使用する前に、関数への両方の呼び出しが正常に戻るのを待つ必要があります。

于 2011-06-30T16:43:16.640 に答える