0

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?

Angelux
  • 89
  • 1
  • 11
  • You create a static style , that is why you have this attitude, use a function to return the style (here is an example-->http://openlayersbook.github.io/ch11-creating-web-map-apps/example-02.html). If you need help , let me know. – pavlos Mar 19 '18 at 13:03

1 Answers1

1

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);
}
Kevin Law
  • 814
  • 4
  • 15
  • Well, I call if features but most of the time there is just one feature in collection. And Im callling this function many times and setting random color for every feature. Problem is, the all features have the color from the last addRoutes calling. For some reason I dont get. – Angelux Mar 19 '18 at 09:52
  • 1
    One more thing, it's not a good way to share features across layers., this may cause many unexpected issue. In another words, you don't need to **new** a vector layer every time you call **addRoutes**, just set the vector layer and vector source as global variable. – Kevin Law Mar 20 '18 at 02:24