上下文:我有一个应用程序,它遍历一个数组,该数组包含要每100毫秒或当用户单击后退/前进按钮时要设置样式的功能ID数组。我当前的实现使用自定义事件侦听器,在其中更新外部数组的索引以获取一组新功能。我首先使用removeFeatureState()清除要素状态,然后对于新内部数组中的每个要素ID,我都使用setFeatureState()来控制样式。
代码:
document.addEventListener('update', function (e) {
var algo_step = run_data[run_index];
map.removeFeatureState(
{source: 'precincts'});
if (algo_step.feasible){
let district_ix = 0;
for(center in algo_step.partition){
algo_step.partition[center].forEach(precinct =>
map.setFeatureState(
{ source: 'precincts', id: precinct },
{ district_n : district_ix }
));
district_ix++;
}
}
else{
algo_step.area.forEach(precinct =>
map.setFeatureState(
{ source: 'precincts', id: precinct },
{ infeasible : true }
));
}
}, false);
问题:运行应用程序时,样式有时无法正确更新。我目前的理解是,这是因为在渲染地图之前未发生对要素状态的异步更新,但我并不肯定。
因此,我认为可以同步更新地图和/或在事件侦听器结束时渲染具有所有特征状态的地图,就可以解决此问题。基于https://github.com/mapbox/mapbox-gl-js/issues/7893,目前尚不清楚是否已实施。
关于如何解决此问题的任何想法?
很难看到它在运行中很难说,但这听起来像是某种竞争条件,当您的更新功能有时花费超过100ms时会发生?
您可以尝试的一件事是等待idle
事件,并偶尔跳过更新。
类似这样的东西:
let idle = true;
map.on('idle', {
idle = true;
});
window.setInterval(() => {
if (!idle) {
return; // still processing something, let's skip
}
idle = false;
var algo_step = run_data[run_index];
// ... rest of update function
}, 100);