[GIS] Writing style function in OpenLayers

geojsonopenlayers

I am attempting to write a style function within an OpenLayers 3 application that will change the fill color of a circle based on an attribute from a GeoJSON piece of data. I have looked over stack exchange and this site as well as the documentation and I still can't crack it. This is what I have:

var wellsLayer = new ol.layer.Vector({
  source: new ol.source.GeoJSON({
    projection: 'EPSG:3857',
    url: 'data/WELLS.geojson'
  }),
  customStyleFunction,

});

This is my best attempt so far:

var customStyleFunction = function(feature, resolution) {

  var fontSize = '18';
  if(feature.get('WELL_CLASS')= 'EXISTING') {
    fontSize = '10';
  } else if(feature.get('WELL_CLASS')= 'PROPOSED') {
    fontSize = '14';
  } else if(feature.get('WELL_CLASS')= 'INJECTION') {
    fontSize = '16';
  }

  return [new ol.style.Style({
    image: new ol.style.Circle({

      fill: new ol.style.Fill({
        color: '9999CC'
      }),
      stroke: new ol.style.Stroke({
        color: '#ddd',
        width: fontSize
      })
    })
  })];
};

I want to call feature.get and grab a field called "WELL_CLASS" which has some values in it. I won't bother detailing everything I have tried but I attempted the hyperlink syntax as well as what is on the ol3 docs with no luck.

It also bears mentioning that I am not very good at JavaScript.


I believe the mistake may be with my function code. I say this because if I define a static style such as below the layer draws without issue, but if I attempt to use the function nothing appears.

 var staticwell = new ol.style.Style({
  image: new ol.style.Circle({
    fill:new ol.style.Fill({color: 'red'}),
    stroke: new ol.style.Stroke({color: 'black', width: 1}),
    radius: 5
  }),
}); 

Best Answer

ran into some problems with the = signs. this is working for me

var customStyleFunction = function(feature, resolution) {


  if(feature.get('WELL_CLASS')=== 'EXISTING') {
    strokecolor = '#020815';
  } else if(feature.get('WELL_CLASS')=== 'PROPOSED') {
    strokecolor = '#f61212';
  } else if(feature.get('WELL_CLASS')=== 'INJECTION') {
    strokecolor = '#198cff';
  }

  return [new ol.style.Style({
    image: new ol.style.Circle({

      fill: new ol.style.Fill({
        color: '#1b465a'
      }),
      stroke: new ol.style.Stroke({
        color: strokecolor,
        width: 3
      }),
      radius: 5
    })
  })];
};

and here is the layer definition:

var wellsLayer = new ol.layer.Vector({
  source: new ol.source.GeoJSON({
    projection: 'EPSG:3857',
    url: "./data/WELLS.geojson"
  }),
  name: 'Wells',
  style: customStyleFunction
});
Related Question