简体   繁体   中英

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. 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.

is there any way how to tell openlayers to generate color for every single feature I add?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM