Skip to content

Instantly share code, notes, and snippets.

@ericjames
Created October 30, 2021 17:11
Show Gist options
  • Save ericjames/03428261c9e843d31d3134431b4810f6 to your computer and use it in GitHub Desktop.
Save ericjames/03428261c9e843d31d3134431b4810f6 to your computer and use it in GitHub Desktop.
Mapbox: Edit new source data on the fly
// You can edit source data on the fly but it requires it to have a layer first, as there is no way to directly access GeoJSON
// GeoJson is only exposed via querySourceFeatures, grabbing features from a map's layer
const yourSourceId = 'some-source';
const url = 'some-url';
map.addSource(yourSourceId, {
type: 'geojson',
data: url
});
map.addLayer({id: 'the-layer', source: yourSourceId, type: '...'});
map.on('sourcedata', editSourceData);
function editSourceData(e) {
if (e.isSourceLoaded && map.querySourceFeatures('the-layer').length > 0) {
const geojson = map.querySourceFeatures('the-layer');
const features = geojson.map((feature) => {
// Do the stuff!!!! Maybe here, reassign properties to the top level
feature.id = feature.properties.SOME_OTHER_ID;
feature.properties.title = "Some new title " + feature.properties.some_other_prop;
return feature;
});
console.log("New features!", features);
const source = map.getSource(yourSourceId).setData({
type: 'FeatureCollection',
features: features
});
map.off('sourcedata', checkData); // Make sure to turn it off when done!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment