【问题标题】:Get Degrees (0-360) from One LatLng to Another in JavaScript在 JavaScript 中从一个 LatLng 到另一个获取度数 (0-360)
【发布时间】:2011-02-23 22:22:37
【问题描述】:

谁能帮我用原生 JavaScript 填补空白?

function getHeading(lat1, lon1, lat2, lon2) {
    // Do cool things with math here

    return heading; // Should be a number between 0 and 360
}

我已经搞砸了很长时间,似乎无法让我的代码正常工作。

【问题讨论】:

    标签: javascript google-maps mapping


    【解决方案1】:

    Chris Veness 在 Bearings 标题下的 Calculate distance, bearing and more between Latitude/Longitude points 有一个非常好的 JavaScript 实现。

    您可能更喜欢使用getHeading 方法扩充Google 的LatLng 原型,如下(使用v3 API):

    Number.prototype.toRad = function() {
       return this * Math.PI / 180;
    }
    
    Number.prototype.toDeg = function() {
       return this * 180 / Math.PI;
    }
    
    google.maps.LatLng.prototype.getHeading = function(point) {
       var lat1 = this.lat().toRad(), lat2 = point.lat().toRad();
       var dLon = (point.lng() - this.lng()).toRad();
    
       var y = Math.sin(dLon) * Math.cos(lat2);
       var x = Math.cos(lat1) * Math.sin(lat2) -
               Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
    
       var brng = Math.atan2(y, x);
    
       return ((brng.toDeg() + 360) % 360);
    }
    

    然后可以这样使用:

    var pointA = new google.maps.LatLng(40.70, -74.00);
    var pointB = new google.maps.LatLng(40.70, -75.00);
    
    pointA.getHeading(pointB);   // Returns 270 degrees
    

    否则,如果您更喜欢全局函数而不是增强 Google 的 LatLng,则可以按以下方式进行:

    function getHeading(lat1, lon1, lat2, lon2) {
        var lat1 = lat1 * Math.PI / 180;
        var lat2 = lat2 * Math.PI / 180;
        var dLon = (lon2 - lon1) * Math.PI / 180;
    
        var y = Math.sin(dLon) * Math.cos(lat2);
        var x = Math.cos(lat1) * Math.sin(lat2) -
                Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
    
        var brng = Math.atan2(y, x);
    
        return (((brng * 180 / Math.PI) + 360) % 360);
    }
    

    用法:

    getHeading(40.70, -74.00, 40.70, -75.00);    // Returns 270 degrees
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2017-01-14
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多