OpenLayers 3:更改要素样式后如何刷新地图?


9

我有一个OpenLayers 3.2.0地图,其中包含一些矢量源(ol.source.Vector)和关联的矢量层(ol.layer.Vector

将功能(ol.Feature)添加到矢量源时,会为它们提供一个data属性,该属性设置为该功能代表的javascript对象。TypeScript跟着...

vectorSource.addFeature(new ol.Feature({
    geometry: /* ... */,
    data: vectorData,
}));

然后,矢量层具有一个样式功能,该功能可以读取data属性并检索其样式:

vectorLayer = new ol.layer.Vector({
    source: vectorSource,
    renderBuffer: /* ... */,
    style: function (feature: ol.Feature, resolution: any) {
        var data = </* TypeScript Type */>feature.get('data');
        if ((data) && (data.style)) {
            return [data.style];
        }
        else {
            /* return default style */
        }
    }
});

有时,与地图无关的事件会导致样式更改。例如,当一个对象变为无效时,其样式会更改。显然,由于data.style完全在我的控制范围内,因此更改它是微不足道的。

问题在于地图不知道样式已更改。如果更改对象的样式,然后缩放地图,迫使它重新绘制,我会注意到我的样式功能运行并返回新样式,并且该特征也被重新绘制。如何以编程方式强制刷新地图?

经过一些搜索和试验,我尝试了:

  1. 调用render()ol.Map本身。
  2. 调用dispatchChangeEvent()ol.source.Vector
  3. 调用redraw()ol.layer.Vector

提出了这些建议,但没有一个可行,这不足为奇,因为OpenLayers 3.2.0 API文档中甚至只列出了第一种方法,并且未将其标记为稳定方法。


您是否尝试过vectorlayer.refresh({force:true}); ?
ylka

我有,但是毫不奇怪,那是行不通的,因为那是OpenLayers 2方法。
Xharlie 2015年

Answers:


12

偶然地,我偶然发现了答案-它是changed()在更改style关联数据的属性后调用特征本身。参见:http : //openlayers.org/en/v3.2.0/apidoc/ol.Feature.html?unstable=true#changed

这确实需要我跟踪ol.Feature与每个vectorData对象关联的对象(以前,我只需vectorData要从某个功能中找到即可,可以使用来完成get()此操作),但这并不是很多费用。

(我通过观察发现,这setGeometrysetStyle和其他方法ol.Feature,看看他们做什么。)


尽管这种方法可行,但changed实际上要求任何合理数量的功能都会导致相当严重的性能损失(以这种方式多次破坏Chrome)。建议changed()您在更改所有功能之后在图层的源上调用。
凯尔(Kyle)

0

我花了一个星期的时间试图弄清楚删除地图项后如何使地图项(多边形)消失(vectorSource.removeFeature(selectedFeature)。并且没有解决方案。奇怪的是,当前的OL3 v3.15.1没有基本的强制刷新/渲染功能,有效的解决方案是更改selectedFeature的样式:

        var newStyle = new ol.style.Style({
            image: new ol.style.Circle({
                radius: 5,
                fill: new ol.style.Fill({color: 'red'}),
                stroke: new ol.style.Stroke({color: 'yellow', width: 1})
            })
        });
        selectedFeature.setStyle(newStyle)

由于样式已从图层中删除但未刷新,因此任何样式均适用。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.