计算地球上2点之间的距离

// 这个函数取2个坐标,一个起点坐标和一个终点坐标,并返回二者之间的距离(千米)
    function computeDistance(startCoords,destCoords){
        var startLatRads = degreesToRadians(startCoords.latitude);
        var startLoingRads = degreesToRadians(startCoords.longitude);
        var destLatRads = degreesToRadians(destCoords.latitude);
        var destLongRads = degreesToRadians(destCoords.longitude);

        var Radius = 6371; //radius of the Earth in km
        var distance = Math.acos(Math.sin(startLatRads) * Math.sin(destLatRads) + Math.cos(startLatRads) * Math.cos(destLatRads) * Math.cos(startLoingRads - destLongRads)) * Radius;

        return distance;
    }

    function degreesToRadians(degrees){
        var radians = (degrees * Math.PI) / 180;
        return radians;
    }

测试:

// 测试
    var startCoords = {
        latitude: 29.8604472,
        longitude:121.498982
    };
    var destCoords = {
        latitude: 47.624851,
        longitude:-122.52099
    };

    var km = computeDistance(startCoords,destCoords);
    alert(km); //9293.980559898791

你可能感兴趣的:(HTML5)