我不知道下一步采取什么方法,目前我有下面的代码,它计算任意两个给定位置(使用长和纬度)之间的英里距离,但是它是一条直线,并且道路不是'直...所以我想要做的是计算谷歌地图的距离,例如这里是一些随机坐标:
lat1: 53.015036674593500
lat2: -2.244633982337860
long1: 52.363731052413800
long2: -1.307122733526320
并且在转换为此代码(JavaScript)时
function distance(lat1, lon1, lat2, lon2, unit) {
var radlat1 = Math.PI * lat1 / 180
var radlat2 = Math.PI * lat2 / 180
var radlon1 = Math.PI * lon1 / 180
var radlon2 = Math.PI * lon2 / 180
var theta = lon1 - lon2
var radtheta = Math.PI * theta / 180
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180 / Math.PI
dist = dist * 60 * 1.1515
if (unit == "K") { dist = dist * 1.609344 }
if (unit == "N") { dist = dist * 0.8684 }
return dist
}
var dist = distance(lata, longa, latb, longb, unit).toFixed(2);
window.alert(dist + " miles");
返回的值是 59.83 里程或者那里...如果我要在谷歌地图中执行此操作:
值介于 77.1英里和 76.5英里
之间问题
我有以下功能PARTLY工作以获取旅行时间和距离,但它会随机返回" UNDEFINED
"在底部的警告框中,或者有此错误消息
"Object doesn't support this action"
使用console.log时会返回以下消息:
"google.maps.DistanceMatrixService is not a function"
代码:
var siteP = postcodearray.indexOf(screen.sitePostcode);
var StaffP = postcodearray.indexOf(screen.engineerPostcode);
sitelat = latarray[siteP];
sitelong = longarray[siteP];
stafflat = latarray[StaffP];
stafflong = longarray[StaffP];
var site = sitelat + ", " + sitelong;
var staff = stafflat + ", " + stafflong;
var distance;
var duration;
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [staff],
destinations: [site],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
distance = response.rows[0].elements[0].distance.text;
duration = response.rows[0].elements[0].duration.text;
//var dvDistance = document.getElementById("dvDistance");
//dvDistance.innerHTML = "";
//dvDistance.innerHTML += "Distance: " + distance + "<br />";
//dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
window.alert(distance); //UNDEFINED
请有人指出我做了什么/我做错了,因为我非常接近我需要的2个值
答案 0 :(得分:2)
您可以在此处找到使用Bing Maps REST服务计算JavaScript中位置之间路线的示例:https://msdn.microsoft.com/en-us/library/gg427607.aspx
我建议添加routeAttributes参数并将其设置为routeSummariesOnly。这将使响应非常小。 https://msdn.microsoft.com/en-us/library/ff701717.aspx
或者,如果您使用的是JavaScript并希望加载地图,请使用Bing Maps JavaScript控件和路线指示模块:https://msdn.microsoft.com/en-us/library/hh312802.aspx
您还可以在此处找到Bing Maps控件的交互式SDK:https://www.bingmapsportal.com/ISDK/AjaxV7#CreateMap1
您需要Bing地图密钥才能访问该服务,但不必将其绑定到参考。我建议您在此处注册免费的Bing地图密钥:https://azure.microsoft.com/en-us/marketplace/partners/bingmaps/mapapis/