I am adding geojson sources from multiple datasets via an internal URI. My addSources() function loops through ds_list
, an array of IDs needed to make each call. If I fetch each dataset in a map.addSource() call, this works (example #1), but then I don't have access to the feature IDs from all datasets, for styling, interaction, etc.
So I want to get each geojson object as a variable, but in example #2, the first dataset is fetched and source/layers rendered, but the following one returns the error
There is already a source with this ID
. the thing is, at the time the second addSource() call is made, the ID (ds.label) has changed, as proven with console.log()
Example #1
# works, but feature IDs are not available
function addSources(ds_list){
sources=[]
for(d in ds_list){
ds = ds_list[d]
mappy.addSource(ds.label, {
'type': 'geojson',
'data': '/datasets/'+ds.id+'/geojson'
});
sources.push(ds.label)
renderSourceLayers(ds.label, d)
}
}
Example #2
# error after 1 dataset: 'There is already a source with this ID'
function addSources(ds_list){
sources=[]
for(d in ds_list){
ds = ds_list[d]
console.log('now doing...', ds.label)
$.getJSON('/datasets/'+ds.id+'/geojson')
.done(function(dsdata) {
mappy.addSource(ds.label, {
'type': 'geojson',
'data': dsdata
});
console.log('just added dsdata', ds.label, dsdata)
sources.push(ds.label)
renderSourceLayers(ds.label, d)
})
}
}
This rendering function works fine for Example #1 and never gets called for second dataset in example #2
renderSourceLayers()
function renderSourceLayers(dslabel, i){
mappy.addLayer({
'id': 'gl_'+dslabel+'_poly',
'type': 'fill',
'source': dslabel,
'visibility': 'visible',
'paint': {
'fill-color': 'rgba(245,245,245, 0.5)',
'fill-opacity': 0.2,
'fill-outline-color': 'black'
},
'filter': ['==', '$type', 'Polygon']
}, 'z-index-1');
mappy.addLayer({
'id': 'gl_'+dslabel+'_point',
'type': 'circle',
'source': dslabel,
'visibility': 'visible',
'paint': {
'circle-color': colors_point[i],
'circle-radius': {
stops: [[1, 2], [3, 3], [16, 20]]
}
},
'filter': ['==', '$type', 'Point']
}, 'z-index-2');
}
The dataset list, for reference. Used for this and to generate a select dropdown, and bounds for flyTo():
ds_list = [
{
"id": 1,
"label": "dataset01",
"title": "wordy title 01",
"bbox": {"type": "Polygon","coordinates": [[],[],[],[],[]]}
},{
"id": 2,
"label": "dataset02",
"title": "wordy title 02",
"bbox": {"type": "Polygon","coordinates": [[],[],[],[],[]]}
}
]