Search code examples
javascriptopenlayersgeojson

Is it possible to extract style information from GeoJson for an openlayers javascript map?


I have a geojson file structured like this:

{
"type": "FeatureCollection",
"features": [{
    "type": "Feature",
    "properties": {
        "marker-color": "#4620dd",
        "marker-size": "medium",
        "marker-symbol": "park",
        "name": "State Park"
    },
    "geometry": {
        "type": "Point",
        "coordinates": [-76.95266723632812,
            39.07974903895123
        ]
    }
}]

}

I am able to create a vector layer from this geojson in an openlayers map, but unable to utilize the styling properties. Should I use a custom style function to do this?


Solution

  • Yes, for sure:

    var vectorLayer = new ol.layer.Vector({
      source: vectorSource,
      style: function (feature, resolution) {
        console.log(feature.getProperties()); // <== all geojson properties
        return [new ol.style.Style({
          image: new ol.style.Circle({
            radius: 10,
            fill: new ol.style.Fill({ color: feature.get('marker-color') })
          })
        })];
      }
    });
    

    https://jsfiddle.net/jonataswalker/uvopawmg/