0
我正在嘗試使用單選按鈕來過濾地圖上顯示的功能。我設法在點擊按鈕時更改矢量源。然而,看起來地圖在最後自動再次使用原始矢量源進行渲染,並覆蓋更新後的矢量源。更改的矢量源不會在OpenLayers v4中保留
var styleCache = {};
var vectorSource = new ol.source.Vector({
url: 'sla.kml',
format: new ol.format.KML({
extractStyles: false
})
});
var clusters = new ol.layer.Vector({
source: new ol.source.Cluster({
distance: 40,
source: vectorSource
}),
style: function(feature) {
var size = feature.get('features').length;
var style = styleCache[size];
if (!style) {
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: '#3399cc'
})
}),
text: new ol.style.Text({
text: size.toString(),
fill: new ol.style.Fill({
color: '#fff'
})
})
});
styleCache[size] = style;
}
return style;
}
});
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var mousePositionControl = new ol.control.MousePosition({
coordinateformat: ol.coordinate.createStringXY(4),
undefinedHTML: ' '
});
var scalelineControl = new ol.control.ScaleLine();
var zoomSlider = new ol.control.ZoomSlider();
var map = new ol.Map({
layers: [raster, clusters],
controls: ol.control.defaults().extend([scalelineControl, zoomSlider]),
renderer: 'canvas',
target: 'map',
view: new ol.View({
center: [-11102324.569458216, 4548521.327621765],
zoom:5
})
});
var count = 0;
var allFeatures;
function changeFeatures(status) {
if (count == 0) {
allFeatures = vectorSource.getFeatures();
}
count++;
// clear all features first, then add them back base on status
vectorSource.clear();
if (status === 'all') {
vectorSource.addFeatures(allFeatures);
} else {
var feature, name;
for (var i = allFeatures.length - 1; i >= 0; --i) {
feature = allFeatures[i];
if (feature.get('status') === status) {
vectorSource.addFeature(feature);
}
}
}
}
vectorSource.on('change', function(evt) {
var source = evt.target;
if (source.getState() === 'ready') {
var numfeatures = source.getFeatures().length;
console.log("feature count after change event: " + numfeatures);
}
});
從控制檯中的輸出顯示:改變事件後
- 特徵計數:9 - >原始特徵
- 特徵計數改變事件後:0 - >後明確矢量源
- 特徵改變事件後計數:1 - >添加一個合格特徵後
- 改變事件後的特徵計數:9 - >似乎用原始矢量源再次渲染地圖(爲什麼?)
爲什麼地圖與原始矢量源再次呈現?我需要做什麼才能使地圖呈現更新後的矢量源?