GeoJSON 对象未出现在 React 应用程序中的 Mapbox 地图上

问题描述 投票:0回答:1

我正在开发一个 React.js 应用程序,我需要在 Mapbox 地图上显示 GeoJSON 对象。地图初始化正确,但 GeoJSON 对象不出现。这是我的代码的相关部分:

useEffect(() => {
  if (map.current) return; // Prevent reinitializing

  map.current = new mapboxgl.Map({
    container: mapContainerRef.current,
    style: 'mapbox://styles/mapbox/streets-v11',
    center: [-97.328, 35.204],
    zoom: zoomLevel
  });

  console.log("THIS APPEARS IN CONSOLE");

  // Wait to do anything until after the map is loaded
  map.current.on('load', () => {
    console.log("THIS DOES NOT APPEAR IN CONSOLE");

    // Add the GeoJSON data as a source
    map.current.addSource('featureData', {
      type: 'geojson',
      data: 'features.geojson' // Update this path to your GeoJSON file
    });

    console.log("NEITHER DOES THIS")

    // Add a layer to display the features
    map.current.addLayer({
      id: 'initialfeatures',
      type: 'symbol',
      source: 'featureData',
      layout: {
        'icon-image': 'airport-15',
        'icon-allow-overlap': true,
        'icon-size': 2
      }
    });
  });
}, []);

这是我的 geojson 文件的示例(此测试中只有 4 个对象)。

  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [35.22242612285483, -97.43936146979259]
      },
      "properties": {
        "object": "traffic signal"

以下是我尝试过的一些事情: 确保正确引用mapContainerRef。 在“加载”事件之前检查错误。 确保我的 geojson 文件位于正确的位置(它位于“public”文件夹中,与 src 文件夹位于同一文件夹中) 验证 Mapbox 访问令牌。 检查网络请求是否有任何失败的请求(注意:加载我的文件的请求不在网络中

reactjs mapbox geojson geo
1个回答
0
投票

@Stefj您的代码有一些问题。

  1. 您的源数据格式不正确。
  2. 您正在为
    symbol
    使用
    addLayer
    类型,并使用
    icon-image
    属性,该属性 需要图像精灵,但您的样式规范中没有定义精灵。
  3. 数据源中的坐标是相反的,当尝试使用不存在的纬度时,Mapbox 会出错(纬度应在 90 到 -90 之间)

对于 #1 - 您在

data:
调用中提供
addSource
道具的对象应该如下所示..

{
    "type": "Feature",
    "geometry": {
      "type": "Point",
      "coordinates": [-97.43936146979259, 35.22242612285483]
    },
    "properties": {
      "title": "Mapbox HQ",
      "marker-symbol": "monument"
    }
}

且不应包含“功能集合”和“功能”。查看有关 GeoJSON 源

规范的更多信息

我使用您的代码设置了一个示例,而不是使用图像精灵,我创建了一个带有

paint
属性的圆形图层来在您想要
icon-image
的位置绘制一个点。 在这里查看该演示

我不确定为什么您没有在

map.current.on('load)
块内看到那些控制台日志语句。他们对我来说表现得很好(参见演示)。

© www.soinside.com 2019 - 2024. All rights reserved.