[GIS] Openlayers style function not working

openlayersstyle

I'm trying to make a vector layer factory function of sorts and I'd like the styles to be as flexible as possible so I've followed various examples and arrived at something which should work but it doesn't display anything on the map. Can anyone suggest what's going wrong please? The code is below and I've also created a fiddle.

var allStyle = {
'Point': new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */({
        anchor: [0.5, 60],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 1,
        scale: 0.5,
        src: 'assets/img/icon/pin.png'
    }))
}),
'LineString': new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: '#f00',
    width: 3
  })
}),
'Polygon': new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(0,255,255,0.5)'
  }),
  stroke: new ol.style.Stroke({
    color: '#0ff',
    width: 1
  })
}),
'MultiPoint': new ol.style.Style({
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */({
        anchor: [0.5, 60],
        anchorXUnits: 'fraction',
        anchorYUnits: 'pixels',
        opacity: 1,
        scale: 0.5,
        src: 'assets/img/icon/pin.png'
    }))
}),
'MultiLineString': new ol.style.Style({
  stroke: new ol.style.Stroke({
    color: '#0f0',
    width: 3
  })
}),
'MultiPolygon': new ol.style.Style({
  fill: new ol.style.Fill({
    color: 'rgba(0,0,255,0.5)'
  }),
  stroke: new ol.style.Stroke({
    color: '#00f',
    width: 1
  })
})
 };

var allStyleFunction = function(feature, resolution) {
var featureStyleFunction = feature.getStyleFunction();
if (featureStyleFunction) {
    console.log('featurestylefunction');
  return featureStyleFunction.call(feature, resolution);
} else {
    console.log('allstyle');
  return allStyle[feature.getGeometry().getType()];
}
};

var vectorSource = new ol.source.Vector();
var vectorLayer = new ol.layer.Vector({ 
source: vectorSource,
style: allStyleFunction
});
map.addLayer(vectorLayer);

Best Answer

I found the same problem. The function should be returning a list of styles not just one. So in your case it must be something like this:

var allStyleFunction = function(feature, resolution) {
    var featureStyleFunction = feature.getStyleFunction();
    if (featureStyleFunction) {
        console.log('featurestylefunction');
        return featureStyleFunction.call(feature, resolution);
    } else {
        console.log('allstyle');
        return [allStyle[feature.getGeometry().getType()]];  // <--- It must be an array.  
    }
};

I tested on my implementation and it works!!!

Related Question