OpenLayers 5 – Styling Vectors Dynamically with JavaScript

javascriptjqueryopenlayers

I have a checkbox button, and I am trying to change the variable getStyle dynamically, when jQuery change event is triggered. Though style property doesn't get updated when the event is triggered.

var style1= new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'khaki'
      }),
       stroke: new ol.style.Stroke({
          color: '#880000',
          width: 2,
          opacity:1
        })
    });

    var style2= new ol.style.Style({
        fill: new ol.style.Fill({
        color: '#5755d900'
      }),
       stroke: new ol.style.Stroke({
          color: 'yellow',
          width: 2,
          opacity:1
        })
    });

     var getStyle = style1; //default style


    $("#layerbg").change(function () { 
      if ($(this).is(':checked')){
        getStyle = style2; //change style when checkbox is ticked
      }
      else{
        getStyle = style1;
      }
    });

    var vector = new ol.layer.Vector({
      style:getStyle, // this variable (getStyle) is not updating
      source: new ol.source.Vector({
      url: 'JS/getjson.json',
      format: new ol.format.GeoJSON()
       }),opacity: 1
    });

Best Answer

It will use the value of getStyle at the time vector is defined. For dynamic styling you need a style function

var vector = new ol.layer.Vector({
  style: function(){ return getStyle; },
  source: new ol.source.Vector({
    url: 'JS/getjson.json',
    format: new ol.format.GeoJSON()
   }),
   opacity: 1
});

or you could use vector.setStyle(getStyle);