【问题标题】:Why are my dataset features IDs undefined in Mapbox GL while I have set them?为什么我在 Mapbox GL 中设置了我的数据集要素 ID 却未定义它们?
【发布时间】:2022-12-21 20:21:22
【问题描述】:

我很难使用 mapbox GL 设置要素 ID。

我有 read,您可以在源代码中使用 generateId:true 自动生成 ID:

是否为 geojson 特性生成 id。启用时, feature.id 属性将根据其在 特征数组,覆盖任何以前的值。

除了我想在其他地方使用我的数据,而不仅仅是 mapbox 地图(除了标记列表);所以我想手动设置它们,因为我希望能够从我的列表中定位我在地图上的特征。所以,我不想在这里使用generateId:true

In the doc,他们的数据集示例就像

  {
    "type": "FeatureCollection",
    "features": [
      {
        "type": "Feature",
        "properties": {
          "id": "marker-iv1qi3x10",//an ID here
          "title": "Burnham Park",
          "description": "A lakefront park on Chicago's south side.",
          "marker-size": "medium",
          "marker-color": "#1087bf",
          "marker-symbol": "marker-blue"
        },
        "geometry": {
          "coordinates": [
            -87.603735,
            41.829985
          ],
          "type": "Point"
        },
        "id": "0de616c939ce2f31676ff0294c78321b"//another ID here
      }
    ]
  }

所以他们在特征对象中有一个 ID "id": "0de616c939ce2f31676ff0294c78321b",在该特征的属性中有另一个 ID "id": "marker-iv1qi3x10"

我猜 mapbox 在内部用于功能的 ID(当 generateId 在您的源代码中设置为 true 时自动生成)是第一个。

假设我手动设置了 ID:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "properties": {
        "id": "customPropId01"
      },
      "geometry": {
        "coordinates": [
          -87.603735,
          41.829985
        ],
        "type": "Point"
      },
      "id": "customID01"
    }
  ]
}

在加载源后检查数据时,我的自定义 ID 仍然存在(使用此代码)。

//when a specific source has been loaded
map.on('sourcedata', (e) => {
  if (e.sourceId !== 'markers') return;
  if (!e.isSourceLoaded) return;
  console.log("SOURCE DATA LOADED",e.source);
});

但是当我点击地图上的标记并记录它时,我的功能的 ID 属性已被删除,现在是 undefined:

我没有使用我的输入源数据来列出我的标记,而是查看了querySourceFeatures,但这没有帮助,因为它只返回地图边界框中的要素——我希望我的列表显示所有要素,这就是为什么我需要在那里使用“原始”源数据。

这真让我抓狂。 有谁知道为什么未设置 ID 以及我该如何解决这个问题?

谢谢 !

【问题讨论】:

    标签: reactjs mapbox-gl-js


    【解决方案1】:

    我发现您可以将 promoteId 设置为要用作 ID 的功能属性:

      map.addSource('markers',{
        type:"geojson",
        data:"http://www.example.com/markers.geojson",
        promoteId:'unique_id'
      })
    

    对于promoteId:'unique_id',我的特性的属性unique_id将用于设置每个特性的ID。

    【讨论】:

    • 这不回答如何保留 feature.id,只回答如何使用 feature.properties.x
    【解决方案2】:

    你的 id 是一个字符串。但是如果你想保留你的 id,这个字符串应该被转换成整数like the doc explain

    特征由它们的 id 属性标识,该属性必须是整数或可以转换为整数的字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多