繁体   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