OpenLayers 6.12快速缩两次级集群要素数量翻倍问题求助
问题描述
基于OpenLayers 6.12开发地图界面,实现集群功能以显示每个集群内的要素数量,但快速连续缩小两次地图级别时,集群显示的要素数量会翻倍(集群要素中出现重复gid的要素,而原始数据仅存在一份)。
问题原因
核心问题在于你给地图绑定了movestart事件,每次地图移动(包括缩放)都会调用centroides_prescriptionsSource.refresh()。这个refresh()方法会让原始数据源重新加载所有要素,当快速连续缩放时,两次refresh()会导致原始要素被重复添加到集群源中,集群统计时就会把重复的要素也算进去,最终数量翻倍。
OpenLayers的Cluster源会自动监听原始数据源的要素变化,频繁调用refresh()会触发多次要素加载,集群源重复处理同一批要素,造成统计错误。
修复方案
直接移除movestart事件的监听和对应的refresh()调用即可。如果你的原始数据不是动态实时更新的,完全不需要在地图移动时强制刷新数据源。如果确实需要刷新数据,应该在数据实际更新时手动调用refresh(),而不是每次地图操作都触发。
修改后的代码示例
// 集群数据源 var clusterSource = new ol.source.Cluster({ distance: 20, source: centroides_prescriptionsSource, }); // 集群图层 var styleCache = {}; var ClusterLayer = new ol.layer.Vector({ source: clusterSource, minResolution: 2, maxResolution: 10500,//2500, style: function(feature2) { var size = feature2.get('features').length; var style = styleCache[size - 1]; if (!style) { if (size <= 50){ style = new ol.style.Style({ image: new ol.style.Circle({ radius: 10, stroke: new ol.style.Stroke({ color: '#fff' }), fill: new ol.style.Fill({ color: 'rgba(204, 153, 255,0.8)' }) }), text: new ol.style.Text({ text: size.toString(), fill: new ol.style.Fill({ color: 'black' }) }), zIndex: size }); } else if (size <= 100){ style = new ol.style.Style({ image: new ol.style.Circle({ radius: 10, stroke: new ol.style.Stroke({ color: '#fff' }), fill: new ol.style.Fill({ color: 'rgba(140, 26, 255,0.8)' }) }), text: new ol.style.Text({ text: size.toString(), fill: new ol.style.Fill({ color: 'white' }) }), zIndex: size }); } else if (size > 100){ style = new ol.style.Style({ image: new ol.style.Circle({ radius: 10, stroke: new ol.style.Stroke({ color: '#fff' }), fill: new ol.style.Fill({ color: 'rgba(77, 0, 153,0.8)' }) }), text: new ol.style.Text({ text: size.toString(), fill: new ol.style.Fill({ color: 'white' }) }), zIndex: size }); } styleCache[size - 1] = style; }; return style; }, name: 'Centroïdes', description: "caviar centroides prescriptions", boutonLegende: true, legendType: 'legende_centroides' }); // 已移除不必要的movestart事件监听
内容的提问来源于stack exchange,提问作者ericire
相关产品推荐
相关产品推荐

