簡體   English   中英

每當我添加功能更改顏色時,Openlayers

[英]Openlayers every time I add feature change color

我有這個功能

 addRoutes(geoJson:{}) {
    let format = new OlFormatGeoJSON({
        featureProjection:"EPSG:3857"
    });

    this._vectorSource.addFeatures(format.readFeatures(geoJson));

    let vectorLayer = new OlVector({
        source: this._vectorSource,
        style: new OlStyle({
            stroke: new OlStyleStroke({
                color: "#"+((1<<24)*Math.random()|0).toString(16),
                width: 10
            })
        })
    });

    this.map.addLayer(vectorLayer);
}

我將帶有功能的geojson傳遞給此函數。 我多次調用此函數。 我想為每個功能生成隨機顏色。 當我使用此功能時,顏色是隨機生成的,但是所有功能都具有相同的顏色。

我需要該vectorSource變量用於搜索所有功能等。

有什么方法可以告訴openlayers為我添加的每個功能生成顏色嗎?

解決您的問題的更好方法是循環功能集合並為每個功能設置樣式。 然后將這些功能僅添加到一層。 似乎您未使用純開放層,因此以下代碼段未經測試, 正式文檔可能會有所幫助。

addRoutes(geoJson: {}) {
    let format = new OlFormatGeoJSON({
        featureProjection: "EPSG:3857"
    });

    let features = format.readFeatures(geoJson)
    features.forEach(f => {
        f.setStyle(new OlStyle({
            stroke: new OlStyleStroke({
                color: "#" + ((1 << 24) * Math.random() | 0).toString(16),
                width: 10
            })
        }))
    })

    this._vectorSource.addFeatures(features);

    let vectorLayer = new OlVector({
        source: this._vectorSource,
    });

    this.map.addLayer(vectorLayer);
}

暫無
暫無

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

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