1

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
    });

1 Answer 1

4

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.