5

我正在使用 Google Maps API 来获取 2 个英国邮政编码之间的距离。

var yourPostcode = $("#YourPostcode").val();
        var restaurantPostcode = $("#Postcode").val();

        var point1 = GetPointFromPostcode(yourPostcode);
        var point2 = GetPointFromPostcode(restaurantPostcode);

        var distance = point1.distanceFrom(point2, 3959).toFixed(1);

但是 GetPoint 函数异步调用 Google API,因此在计算距离时 point1 和 2 尚未设置(我相信这是发生了什么?)

我还在每条语句后放置警报以检查变量的值,这样做我得到了正确的距离值,等待我点击确定必须给它足够的时间来获得结果吗?虽然它不再这样做了:(

这是获取点功能

function GetPointFromPostcode(postcode) {
    var point;
    localSearch.execute(postcode + ", UK");
    if (localSearch.results[0]) {
        var resultLat = localSearch.results[0].lat;
        var resultLng = localSearch.results[0].lng;

        point = new GLatLng(resultLat, resultLng);

    } else {
        $(".PostcodeError").append("Postcode Invalid");
    }
    return point;
}

我知道我可以在本地搜索上设置回调,以便在结果返回时调用,但这里的问题是有 2 个搜索。

我想要的是仅在两次搜索都返回结果后才调用计算距离线。

你知道我怎么能做到这一点吗?

谢谢

4

2 回答 2

4

如果您能够获取每个邮政编码的 GPS 坐标(纬度、经度),请构建一个 Javascript 距离函数。

C# 中找到它,但如果你想在 JS 中重现它,概念是相同的。

于 2009-08-29T15:01:13.187 回答
0

这可能有效 - 本质上是根据它是在搜索第一个邮政编码还是第二个邮政编码,将 setSearchCompleteCallback 做出不同的反应。

var searchControl= new google.search.SearchControl();
var distanceSearch = new google.search.LocalSearch();
searchControl.addSearcher(distanceSearch);

distanceSearch.setSearchCompleteCallback(null, function() {
    if(distanceSearch.results.length > 0 && distanceSearch.postcode2)
    {
       distanceSearch.point1 = new GLatLng(distanceSearch.results[0].lat, distanceSearch.results[0].lng)
       var postcode2 = distanceSearch.postcode2;
       distanceSearch.postcode2 = null;             
       distanceSearch.execute(postcode2 + ", UK");
    } else if (distanceSearch.results.length > 0 && !distanceSearch.postcode2) {
       distanceSearch.point2 = new GLatLng(distanceSearch.results[0].lat, distanceSearch.results[0].lng)
       //some code to calculate distance and write it to somewhere
    } else {
       //no search results
    }
});

function measureDistance(postcode1, postcode2) { 
    distanceSearch.postcode2 = postcode2;
    distanceSearch.execute(postcode1 + ", UK");
}
于 2009-08-30T00:27:11.887 回答