首页 > 解决方案 > 在 React 中将 mapbox 线变成 turf.js 曲线(贝塞尔)线

问题描述

我正在尝试找到一种方法将常规 mapbox 线变成Turf.js提供的贝塞尔曲线

那里的片段并不是特别有用——它们有一个addToMap变量,但没有说明如何处理它——我似乎无法弄清楚如何在 React 中将线添加到地图中。

这就是我当前绘制默认/直线的方式:

const [route] = useState<FeatureCollection<LineString>>({
type: 'FeatureCollection',
features: [
  {
    type: 'Feature',
    geometry: {
      type: 'LineString',
      coordinates: [
        [originAirport.longitude, originAirport.latitude],
        [destinationAirport.longitude, destinationAirport.latitude],
      ],
    },
    properties: {},
  },
],

}); const [lineLayer] = useState({ id: 'route', source: 'route', type: 'line', paint: { 'line-width': 2, 'line-color': '#007cbf', }, });

稍后,在返回中:

<Source
    id="map-line"
    type="geojson"
    data={{
      ...route,
      features: [
        {
          ...route.features[0],
          geometry: {
            ...route.features[0].geometry,
            coordinates: [
              [originAirport.longitude, originAirport.latitude],
              [destinationAirport.longitude, destinationAirport.latitude],
            ],
          },
        },
      ],
    }}
  >
    <Layer {...lineLayer} />
  </Source>

我尝试将坐标包装在turf.bezierSplinefn 中,但失败了。找不到其他方法来添加它。

我正在使用react-mapb-gl,但没有太多将它与 turf.js 集成的内容。我还尝试添加一个额外的源层,如下所示:

const line = turf.lineString([
  [-76.091308, 18.427501],
  [-76.695556, 18.729501],
]);

const curved = turf.bezierSpline(line);

在回报:

<Source id="test" type="geojson" data={curved}>
  <Layer {...lineLayer} />
</Source>

标签: javascriptreactjsmapboxgeojsonturfjs

解决方案


对于任何回到这个线程的人:

问题在于我将数据传递给Source. 如果您控制台记录由返回的数据curved,它不会FeatureCollection像我存储在route状态变量中那样返回一个整体;它只返回一个功能。所以数据应该Source像这样传递:

<Source id="test" type="geojson" data={{ ...route, features: [curved] }}>
  <Layer {...lineLayer} />
</Source>

推荐阅读