我正在使用 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 个搜索。
我想要的是仅在两次搜索都返回结果后才调用计算距离线。
你知道我怎么能做到这一点吗?
谢谢