首页 > 解决方案 > Mapbox:在 onClick() 中使用 REST API 调用创建自定义绘制模式

问题描述

我正在尝试使用该@mapbox/mapbox-gl-draw库创建自定义绘制模式。我希望该模式允许用户通过在地图上放置点来创建路线。每个点放置好后,我想调用 Mapbox Map Matching API 来查找上一个点和当前点之间的路线,然后渲染结果线。

我面临的问题是,在地图上放置另一个点或用户切换模式之前,该线不会被渲染。我猜这个问题是由于对 Map Matching 的 API 调用返回了一个承诺,尽管我离 Mapbox 专家最远(几天前才开始使用它)。

我将附上该问题的视频剪辑,希望它比我能更好地描述问题:https ://streamable.com/ao3ger

DrawRoute 模式onClick函数如下所示:

DrawRoute.onClick = function (state, e) {
  var point = this.newFeature({
    type: 'Feature',
    properties: {
      count: state.count,
    },
    geometry: {
      type: 'Point',
      coordinates: [e.lngLat.lng, e.lngLat.lat],
    },
  });

  const features = this._ctx.store._features;

  if (Object.keys(features).length > 0) {

    const lastPoint = getLastPointDrawn(features)

    const coordinates = `${lastPoint.coordinates[0]},${lastPoint.coordinates[1]};${point.coordinates[0]},${point.coordinates[1]}`;

    // This is an async function that makes a call to the Map Matching API and returns the line coordinates
    getMatch(coordinates, [25, 25], 'walking').then((lineCoordinates) => {
      // Add new line feature to object here using coords
      const line = this.newFeature({
        type: 'Feature',
        properties: {},
        geometry: {
          type: 'LineString',
          coordinates: lineCoordinates,
        },
      });

      this.addFeature(line);
    });
  }
  this.addFeature(point);
};

这是onDisplayFeatures方法:

DrawRoute.toDisplayFeatures = function (state, geojson, display) {
  display(geojson);
};

有人对 Mapbox 如何呈现每个功能有指导吗?我可以看到,DrawRoute每次用户单击时,该对象都包含新的线要素,但toDisplayFeatures直到创建下一个点时它们才会传递给。谢谢!

标签: javascriptmapboxmapbox-gl-draw

解决方案


推荐阅读