Home > other >  Angular - use checkboxes to display/remove layers on a Leaflet map
Angular - use checkboxes to display/remove layers on a Leaflet map

Time:04-06

I'm working on Angular CLI in which I've built a Leaflet Map.
The goal is to select layers with checkboxes to display them in the map as the HTML part is showing :

 <div >
 <input  type="checkbox" (change)="testCheck($event)" name="releves">
 <label >Layer 1</label>
 </div>

When I select "Layer1", the checkbox is checked and that runs the testCheck($event).

As the Typescript part is showing, I added lines of code to display the layer on the map :

 testCheck(event: any){
      if (event.target.name == 'releves'){
         var releves = L.tileLayer.wms('https://URL_TO_THE_WMS', {layers: 'myLayer',format: 'image/png',transparent:true});
         if (event.target.checked === true){ 
                 if (! this.mymap.hasLayer(releves)) {
                    releves.addTo(this.mymap);
                 }
                 else if (this.mymap.hasLayer(releves)) {
                    // do nothing
                 }
            let i = 0;
            this.mymap.eachLayer(function(){ i  = 1; });
            console.log('Map has', i, 'layers.');
         }
         else {
                if (this.mymap.hasLayer(releves)) {
                    console.log ("has layer 1");
                    this.mymap.removeLayer(releves);
                }
            }
        }
    }

The Layer 1 is well displayed on the map, no problem here (see releves.addTo(this.mymap)). But I have two problems I can't resolve :

  1. When I uncheck "Layer 1" (means event.target.name is not true in the else condition part), the layer is not removed whereas I use the removeLayer method.
  2. The hasLayer method does not seem to work. Indeed after having displayed the layer 1, when I uncheck and test if the layer is present, I should get the console.log message "has layer 1" before the removal. But there's nothing...

May you know how to debug that ?
Any help would be very appreciated, thanks

CodePudding user response:

You create a brand new releves layer everytime the testCheck method is called, so hasLayer(releves) will always be false.

Store your layer in a "permanent" state, typically as a member of your Angular component, exactly like you do for mymap:

@Component({})
export class MyComponent {
  releves = L.tileLayer.wms();

  testCheck(event) {
    if (this.mymap.hasLayer(this.releves)) {
      // etc.
    }
  }
}
  • Related