简体   繁体   English

每当我添加功能更改颜色时,Openlayers

[英]Openlayers every time I add feature change color

I have this function 我有这个功能

 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);
}

I pass a geojson with feature to this function. 我将带有功能的geojson传递给此函数。 I'm calling this function many times. 我多次调用此函数。 And I want to generate random color for each feature. 我想为每个功能生成随机颜色。 When I use this function the color is generated randomly but all features have the same color. 当我使用此功能时,颜色是随机生成的,但是所有功能都具有相同的颜色。

I need to have that vectorSource variable for searching in all features etc. 我需要该vectorSource变量用于搜索所有功能等。

is there any way how to tell openlayers to generate color for every single feature I add? 有什么方法可以告诉openlayers为我添加的每个功能生成颜色吗?

A better approach to your case is loop the features collection and set style for each feature. 解决您的问题的更好方法是循环功能集合并为每个功能设置样式。 Then add these features to just one layer. 然后将这些功能仅添加到一层。 And seems you are not using pure openlayers, so following code snippet has not been tested, Official document could be helpful. 似乎您未使用纯开放层,因此以下代码段未经测试, 正式文档可能会有所帮助。

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