0

我尝试使用google maps api获取两点之间的距离,

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)));

    }

问题是当我尝试时似乎首先执行警报,然后执行地理编码部分,当然 distanceFrom 方法失败,因为 firstZip 和 secondZip 的值未定义。有人知道如何解决吗?

4

1 回答 1

1

getLatLng函数是异步的,因此您需要等待对它的两次调用都成功返回,然后再尝试使用firstZipandsecondZip变量。

于 2011-06-30T16:43:16.640 回答