我正在使用 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 个搜索。
我想要的是仅在两次搜索都返回结果后才调用计算距离线。
你知道我该怎么做吗?
谢谢
最佳答案
如果您能够获取每个邮政编码的 GPS 坐标(纬度、经度),请构建一个 Javascript 距离函数。
找到它 here在 C# 中,但如果您想在 JS 中重现它,概念是相同的。
关于javascript - 2个邮政编码之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1351619/