JavascriptはGPS 2点の経緯度情報に基づいて距離を計算します.

3895 ワード

//    
const EARTH_RADIUS = 6378137.0; //  M
//PI 
const PI = Math.PI;
function getRad(d) {
    return d * PI / 180.0;
}
/**
 *   GPS           
 * @param  {Number} latitude1  1 GPS   
 * @param  {Number} longitude1  1 GPS   
 * @param  {Number} latitude2  2 GPS   
 * @param  {Number} longitude2  2 GPS   
 * @return {Number}               
 */
function getFlatternDistance(latitude1, longitude1, latitude2, longitude2) {
    if ((latitude1 === latitude2) && (longitude1 === longitude2)) {
        return 0;
    }
var lat1 = latitude1;
    var lng1 = longitude1;
    var lat2 = latitude2;
    var lng2 = longitude2;

    if (lat1 == null || lng1 == null ||
        lat2 == null || lng2 == null) {
return Number.NaN;
    }


    var f = getRad((lat1 + lat2) / 2);
    var g = getRad((lat1 - lat2) / 2);
    var l = getRad((lng1 - lng2) / 2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;

    var tValue = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
return tValue;
};