我正在通过内部URI从多个数据集中添加geojson源。我的addSources()函数遍历ds_list,这是进行每次调用所需的ID数组。如果我在map.addSource()调用中获取每个数据集,这是可行的(示例#1),但是我无法访问所有数据集中的特性ID,以进行样式设置、交互等。
因此,我希望将每个geojson对象作为变量获取,但在示例#2中,获取了第一个数据集并渲染了源/层,但下面的示例返回错误There is already a source with this ID。问题是,在进行第二个addSource()调用时,ID (ds.label)已经更改,如console.log()所证明的那样
示例#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)
}
}示例#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)
})
}
}此呈现函数在示例#1中运行良好,并且在示例#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');
}数据集列表,以供参考。用于此操作并生成一个select下拉列表,以及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": [[],[],[],[],[]]}
}
]发布于 2021-07-31 16:16:02
问题在于$.getJSON的异步特性,我很尴尬地说,答案很简单:使用map.forEach(),在本例中...
function addSources(ds_list){
ds_list.forEach(function(ds,i){
$.getJSON('/datasets/'+ds.id+'/geojson')
.done(function(dsdata) {
mappy.addSource(ds.label, {
'type': 'geojson',
'data': dsdata
});
renderSourceLayers(ds.label, i)
})
})
} 以前从来没有这样使用过javascript Map。Live和learn...publicly
https://stackoverflow.com/questions/68596195
复制相似问题