我试图用谷歌api的两种不同方法找到两点p1和p2之间的距离......
这是代码......
var directionsService = new google.maps.DirectionsService();
var p1 = new google.maps.LatLng(45.463688, 9.18814);
var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);
var request = {
origin: p1,//'Melbourne VIC', // a city, full address, landmark etc
destination: p2,// 'Sydney NSW',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(response.routes[0].legs[0].distance.value/1000); // the distance in metres
//console.log(response.routes[0].legs[0].duration.value);
}
else {
// oops, there's no route between these two locations
// every time this happens, a kitten dies
// so please, ensure your address is formatted properly
}
console.log(calcDistance(p1, p2));
//if(!(parseFloat("hello"))) console.log(parseFloat("12.222"));
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
});
我得到的输出如下...... 103.847 //第一个日志 78.35 //第二个日志
有人可以解释一下为什么会出现这种差异......我在哪里错了......
答案 0 :(得分:2)
您使用的第一种方法是googles方向服务请求,当您将旅行模式设置为DRIVING
时,此响应是沿道路的两个点之间的一组方向。距离是你必须开车的距离。
第二种方法是几何库,并返回穿过球体的最短路径,该球体是两点之间的世界(the great-circle distance)。因此,距离2较短,因为它是直接的,而距离1是假设您想要使用道路的实际行驶距离。