【问题标题】:Is there a way to calculate the bearing from one point to another?有没有办法计算从一点到另一点的方位?
【发布时间】:2016-03-19 00:00:10
【问题描述】:

这就是我手动操作的方式...

我有这三个坐标:

var coordinateOne   = [-72.642883, 42.201343];
var coordinateTwo   = [-72.639532, 42.200784];
var coordinateThree = [-72.637823, 42.199687];

我有这张地图,它以第一个坐标为中心:

var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v8',
  center: coordinateOne,
  zoom: 19
});

我可以手动设置方位角,使下一个坐标(不准确,但对于本例来说足够接近)直接向前:

map.easeTo({ bearing:109, pitch:60, zoom:19 });

然后我可以直接飞到第二个坐标:

map.flyTo({ center:coordinateTwo, zoom: 19 });

然后我可以再次手动设置方位,将第三个坐标直接放在前面:

map.easeTo({ bearing:130, pitch:60, zoom:19 });

然后我可以直接飞到第三个坐标:

map.flyTo({ center:coordinateThree, zoom: 19 });

有没有办法每次都自动计算出方位值,让每个flyTo一直往前走?


我找到了this question,它在 Java 中涵盖了这个想法。根据那里的代码,我想出了以下代码,它 close 但与它有更多的垂直角度,而不是直接对齐下一个点。

function bearing(lat1, lon1, lat2, lon2) {
  var longDiff = lon2 - lon1;
  var y        = Math.sin(longDiff) * Math.cos(lat2);
  var x        = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(longDiff);

  return ( toDegrees( Math.atan2( y, x ) ) + 360 ) % 360;
}

function toDegrees (angle) {
  return angle * (180 / Math.PI);
}

【问题讨论】:

    标签: javascript mapbox mapbox-gl-js


    【解决方案1】:

    我发现TurfJS 包含bearing 测量值,所以我正在使用它。

    我把这个函数放在一起来返回两点之间的方位:

    function bearingBetween(coordinate1, coordinate2) {
      var point1 = {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [coordinate1[0], coordinate1[1]]
        }
      };
      var point2 = {
        "type": "Feature",
        "geometry": {
          "type": "Point",
          "coordinates": [coordinate2[0], coordinate2[1]]
        }
      };
      return turf.bearing(point1, point2);
    }
    

    我在我的easeTo 行中使用它:

    map.easeTo({ bearing: bearingBetween(coordinateOne, coordinateTwo), pitch: 60, zoom: 19 });
    

    TurfJS 用于计算此值的代码在其packages/turf-bearing/index.js 文件中。

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-20
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多