簡體   English   中英

如何從開放圖層中的矢量圖層的單個特征中刪除樣式?

[英]How to remove style from individual feature of a Vector Layer in Open Layers?

我正在學習 JS 的 OpenLayers 庫。 我已經成功設置了一個單擊事件來更改單個功能的樣式。 但是,一旦我點擊了其他地方或其他功能,我想刪除該樣式。

var white = [255, 255, 255, 1];
var blue = [0, 153, 255, 1];
var width = 3;

// Basic Style for the point layer
const pointStyle = new ol.style.Style({
    image: new ol.style.Circle({
        radius: width * 2,
        fill: new ol.style.Fill({
            color: blue
        }),
    }),
})
const map = new ol.Map({
    //Some Parameters
})

const points = new ol.layer.Vector({
    source: new ol.source.Vector({
        url: './res/points.json',
        format: new ol.format.GeoJSON(),
    }),
    style: pointStyle,
    title: 'Points'
})

const myLayerGroup = new ol.layer.Group({
    layers: [boundary, points]
})
map.addLayer(myLayerGroup);

map.on('click', function(e) {
    map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
        if (feature.get('Name')) {
            if (feature.getStyle() == null) {
                layer.setStyle(pointStyle);
                feature.setStyle(); //Tried setting style to null here, didn't work
                feature.setStyle(new ol.style.Style({
                    image: new ol.style.Circle({
                        radius: width * 2,
                        fill: new ol.style.Fill({
                            color: white //Basically points change to white here
                        }),
                    })
                }))
            }
        }
    })
})

我似乎一旦為單個元素設置了樣式,即使我覆蓋了整個圖層的樣式,單個元素的樣式仍然存在。 我還沒有找到一種方法來遍歷每個功能並將它們各自的 styles 設置為空白。

您可以使用變量來記錄更改了哪個功能

let changedFeature;
map.on('click', function(e) {
    if (changedFeature)
        changedFeature.setStyle();
        changedFeature = undefined;
    }
    map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
        if (feature.get('Name')) {
            if (feature.getStyle() == null) {
                feature.setStyle(new ol.style.Style({
                    image: new ol.style.Circle({
                        radius: width * 2,
                        fill: new ol.style.Fill({
                            color: white //Basically points change to white here
                        }),
                    })
                }))
                changedFeature = feature;
            }
        }
    })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM