Search code examples
javascriptmapsopenlayers

Set icons source from GeoJSON properties in OpenLayers


I'm trying to build a map with OpenLayers, from a GeoJSON file where I have a property iconUrl for each point. I want that my style refers to that property, and I can't manage to do it. I did it with Leaflet, you can see the goal here: https://idrissad.github.io/lyon_map/

Here is my OL code:

function styleFunction(feature) {
  if (feature.get('iconUrl')) {
    var iconUrl = feature.get('iconUrl');
    console.log(iconUrl);
  }
  var defaultStyle = new ol.style.Style({
   fill: new ol.style.Fill({
    color: "green"
  }),
  stroke: new ol.style.Stroke({
   color: "green",
   width: 1.2
  }),
  image: new ol.style.Icon({
   scale: 0.1,
   src: iconUrl
  })
 })return [defaultStyle]
}

And:

const data = new ol.layer.Vector({
  source: new ol.source.Vector({
   url:'data.geojson',
   format: new ol.format.GeoJSON
  }),
  style: styleFunction,
  visible: true
})

The error I get is "Assertion failed:6 => A defined and non-empty src or image must be provided." I tried several options, without success. My console.log shows me that the feature.get() works fine, I have my urls in the var iconUrl. Any clue?


Solution

  • As you also have fill and stroke is your style is it also being used for polygons? If other features don't have an iconUrl that will cause the error. Try modifying the style function so the image part is only set if there is an iconUrl

    function styleFunction(feature) {
      var iconUrl = feature.get('iconUrl');
      var defaultStyle = new ol.style.Style({
        fill: new ol.style.Fill({
        color: "green"
      }),
      stroke: new ol.style.Stroke({
       color: "green",
       width: 1.2
      }),
      image: iconUrl ? new ol.style.Icon({
       scale: 0.1,
       src: iconUrl
      }) : undefined
     });
     return [defaultStyle];
    }