0

I am using OpenLayers 6.

I need to show/hide layers on a map, by using a multiple select. The multiple select generates an array which should be matched with the layers on the map. These are grouped in a second array.

var region_selected = ["Area 1", "Area 2", "Area 3"]

(function($) {
for (k = 0; k < region_selected.length; ++k){
    var reg = region_selected[k];

    for (i = 0; i < layers_group.length; ++i){
      var layer_region = layers_group[i].get('name');

      if(reg === layer_region){
        layers_group[i].setVisible(true);
      }  
      else {
        layers_group[i].setVisible(false);
      }
    }
  }
});

The result is that the last element of the array region_selected is visible, because when one condition is true for the first iteration, then it is no more true for the second iteration and so on.

Since I have this problem also with the layer's features, is there a solution?

A POSSIBLE SOLUTION

I found a solution by setting all layers invisible when the multiple select is triggered. I don't know if there are better solutions. This however works, and I added the possibility of select "all" layers together.

(function($) {
var j;
for (j = 0; j < layers_group.length; ++j){
  layers_group[j].setVisible(false);
  };

for (k = 0; k < region_selected.length; ++k){
    var reg = region_selected[k];
    if (reg == "all") {
      for (y = 0; y < layers_group.length; ++y){
        layers_group[y].setVisible(true);
        };
    }
    else {
      for (i = 0; i < layers_group.length; ++i){
        var layer_region = layers_group[i].get('name');
        if(reg === layer_region){
          layers_group[i].setVisible(true);
        }  
      }
    }
  }

});

2
  • What would be criteria for the "better"? If your solution works as desired, why would you want something "better"?
    – TomazicM
    Sep 15, 2022 at 13:49
  • @ TomazicM my criteria for "better" are basically to avoid redundancy in my script. But yes you are right, given that the above works. Sep 15, 2022 at 15:15

1 Answer 1

0

It's always nice to try to make code "better", that's how you learn. If you want something "better" just do one loop over your layers_group and use more native array functions.

layers_group.forEach((group)=> {
  const name = group.get('name');
  const visible = region_selected.includes('all') || region_selected.includes(name);
  group.setVisible(visible);
};

I didn't test the code. ;)

1
  • Thanks @oterral, you code seems working and it is much compact than mine. Oct 4, 2022 at 12:00

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.