Search code examples
openlayersopenlayers-5

OpenLayers automatically style line features


Is there any way to automatically style each feature read from a GeoJSON File and used as a source for a vectorlayer differently? I’ve attached a screenshot: This mess of green line features is more than confusing. It would be nice for each line to have a different color randomly assigned to it. Thanks for your help!

enter image description here

Edit: Added Code

Here you find the relevant Code I’m using for this representation. You can see that I define green as the color für LineStrings, but I’m wondering how I can automate the allocation of different colors to LineStrings.

// load GeoJSON with > 2000 Line Features
var fullGeoJSON = require("./data/datafile.json");
// Style function to be called in Layer definition, uses Styles defined in var styles
var styleFunction = function (feature) {
    return styles[feature.getGeometry().getType()];
};
// Define Style (one for all)
var styles = {
    "Point": new Style({
        image: image
    }),
    "LineString": new Style({
        stroke: new Stroke({
            color: "green",
            width: 3
        })
    }),
};
// Define Source
var geoSource = new VectorSource({
    features: new GeoJSON().readFeatures(fullGeoJSON, {
        featureProjection: "EPSG:3857"
    })
});
// Define Layer
var baseLayer = new VectorLayer({
    source: geoSource,
    style: styleFunction
});
// Define Map
const mainMap = new Map({
    target: "map-container",
    layers: [baseLayer],
    view: initialView
});

Solution

  • I figured it out thanks to all the help from your comments:

    1. Load chroma.js into your project (I use npm and webpack and after installing it with npm I require chroma like this: var chroma = require("chroma-js");)
    2. Define a randomize function:

      function randomize() {
          geoSource.forEachFeature(function (feature) {
              var scale = chroma.scale(["#731422", "#1CBD20", "#1CA1FF"]).mode("lch").colors(300); // Define color scale
              var randomColor = scale[Math.floor(Math.random() * scale.length)]; // select a random color from color scale
              var randomStyle = new Style({
                  stroke: new Stroke({
                      color: randomColor,
                      width: 5
                  })
              }); // define a style variable
              feature.setStyle(randomStyle); // set feature Style
          });
      }
      
    3. call the function once and whenever the layer chnages: randomize();

    4. "Define" Layer, this time without a style:

      var baseLayer = new VectorLayer({
          source: geoSource
      });
      

    enter image description here