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 [
          new ol.style.Style({
            stroke: new ol.style.Stroke({ width: 1.5, color: [0,0,0]}),

enter image description here

  • 2
    You would need some property of GeoJSON features to be used as a basis for assigning colors. Please edit your question and add an example of your GeoJSON features.
    – TomazicM
    Commented Sep 23, 2020 at 18:32
  • i found in the documentation of openlayers , that there is a property called "setStyle(opt_style)" ,it's can help me or no ?
    – work
    Commented Sep 23, 2020 at 20:28
  • @work You can create a function to select a color based on feature properties and call that function inside style function. you can find style functions here Commented Oct 9, 2020 at 13:43

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.