1

そこで、以下に示すように、マイルを使用して、Google マップから取得したルートに沿った場所を見つけるための Haversine 式を実行しました。

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 に答える