'Why are my dataset features IDs undefined in Mapbox GL while I have set them?
I struggle to set feature IDs using mapbox GL.
I've read that you can auto-generate IDs using generateId:true in your source:
Whether to generate ids for the geojson features. When enabled, the feature.id property will be auto assigned based on its index in the features array, over-writing any previous values.
Except that I want to use my data at other places than just the mapbox map (a list of markers aside); so I would like to set them manually because I want to be able to target my feature on the map from my list aside. So, I don't want to use generateId:true here.
In the doc, their dataset example is like
{
"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
}
]
}
So they have an ID in the feature object "id": "0de616c939ce2f31676ff0294c78321b", and another ID in the properties of that feature "id": "marker-iv1qi3x10".
I guess that the ID that mapbox uses internally for features (and auto-generated when generateId is set to true in your source) is the first one.
Let's say I set the IDs manually:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"id": "customPropId01"
},
"geometry": {
"coordinates": [
-87.603735,
41.829985
],
"type": "Point"
},
"id": "customID01"
}
]
}
When inspecting the data when the source has loaded, my custom IDs are still in place (using this code).
//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);
});
But when I click on a marker on the map and that I log it, the ID property of my feature has been removed and is now undefined:
Rather than using my input source data to list my markers, I also had a look at querySourceFeatures, but this doesn't help since it returns only the features in the map bouding box - and I want my listing to display all the features, that is why I need to use the "raw" source data there.
This is driving me crazy. Does anyone knows why the IDs are unset and how I could fix this ?
Thanks !
Solution 1:[1]
I found out that you can set promoteId to the feature property you want to use as IDs :
map.addSource('markers',{
type:"geojson",
data:"http://www.example.com/markers.geojson",
promoteId:'unique_id'
})
With promoteId:'unique_id', the property unique_id of my features will be used to set each feature's ID.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gordie |

