TransWikia.com

Changing the color of every entity of GeoJSON layer in OpenLayers 6.4.3

Geographic Information Systems Asked on December 18, 2020

I would like to change the color of every entity of my GeoJSON, like in the picture. For now I can just change all the features with the same color.

Here is my code:

const provinceGeoJSON = new ol.layer.VectorImage({
          source: new ol.source.Vector({
              url: './data/chefchaouen.geojson',
              format: new ol.format.GeoJSON(),
              attributions: [ "&copy; <a href='https://www.insee.fr'>INSEE</a>", "&copy; <a href='https://www.data.gouv.fr/fr/datasets/geofla-r/'>IGN</a>" ],

          }),
          
          title: 'provinceGeoJSON',
          style: function (f) {
        return [
          style,
          new ol.style.Style({
            stroke: new ol.style.Stroke({ width: 1.5, color: [0,0,0]}),
           
          })
        ]
      }

enter image description here

One Answer

provinceGeoJSON.getSource().getFeatures().map(feature => {
    let r = Math.round(Math.random() * 255);
    let g = Math.round(Math.random() * 255);
    let b = Math.round(Math.random() * 255);
    feature.setStyle(new Style({
        fill: new Fill({
           color: `rgba(${r}, ${g}, ${b}, .7)`
        }),
        stroke: new Stroke({
           color: `rgb(${r}, ${g}, ${b})`
        })
    }))
});

In the above example I loop through the features of your layer and for each one I generate a random color. In your case you should probably have your colors predefined in another array with length equal to the number of your features. Best case scenario is to have them predefined in your database together with your geoJSON so the mapping will be easier. Also, if you do that there is no need to set a style on the layer itself.

Answered by George Makroglou on December 18, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP