2017-07-15 21 views
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 - >似乎用原始矢量源再次渲染地图(为什么?)

为什么地图与原始矢量源再次呈现?我需要做什么才能使地图呈现更新后的矢量源?

回答

1

当源配置url时,在其上调用#clear()将触发重新加载。

您可以在矢量图层上设置新的源(使用ol.layer.Vector#setSource()),也可以使用初始配置创建vectorSource而不使用url。我会推荐前者。