1

因此,我使用 Haversine 公式继续查找从 Google 地图检索到的路线沿线的位置,如下所示,使用英里。

var R = 3959 //in miles;
var lat1 = result.routes[0].overview_path[index].k.toFixed(5);
var lat2 = locations[index2].lat;
var lon1 = result.routes[0].overview_path[index].A.toFixed(5);
var lon2 = locations[index2].lng;
var deltaLat = (lat2-lat1).toRad();
var deltaLon = (lon2-lon1).toRad();
var a = Math.sin(deltaLat/2)*Math.sin(deltaLat/2) + Math.cos(lat1) * Math.cos(lat2) *
                Math.sin(deltaLon/2)*Math.sin(deltaLon/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R*c;

但是当它使用点(例如)36.64756、-97.34593(在威奇托、堪萨斯州和达拉斯之间的路径上)和 39.933321、-91.409415(在伊利诺伊州昆西的一个位置)时,我的距离不到 20 英里。显然这是不正确的。我无法用其他值复制错误 - 我偶然发生了这个。

这是toRad原型,顺便说一句-

if(typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function(){
    return this * Math.PI / 180;
};
}

我最初的猜测是某处的浮点溢出,但我无法使用 toFixed 隔离或缓解它。有人有想法么?

4

3 回答 3

2

我相信你的等式是错误的。这是您可以比较的 javascript 版本:http ://www.movable-type.co.uk/scripts/latlong.html

不同的是你的条款Math.cos(lat1) * Math.cos(lat2)。您需要先将lat1和转换lat2为弧度。

于 2014-05-07T19:25:39.603 回答
2

toFixed 返回带有值的字符串,记住这一点。

http://www.w3schools.com/jsref/jsref_tofixed.asp

于 2014-05-07T18:57:44.673 回答
0

您可以在这里使用我的包为您计算:https ://www.npmjs.com/package/haversine-calculator

const haversineCalculator = require('haversine-calculator')

const start = {
  latitude: -23.754842,
  longitude: -46.676781
}

const end = {
  latitude: -23.549588,
  longitude: -46.693210
}

console.log(haversineCalculator(start, end))
console.log(haversineCalculator(start, end, {unit: 'meter'}))
console.log(haversineCalculator(start, end, {unit: 'mile'}))
console.log(haversineCalculator(start, end, {threshold: 1}))
console.log(haversineCalculator(start, end, {threshold: 1, unit: 'meter'}))
console.log(haversineCalculator(start, end, {threshold: 1, unit: 'mile'}))

看一下,我认为这段代码比手动编写更容易维护和灵活。

于 2018-05-17T00:37:14.743 回答