Search code examples
angularleafletionic4overlapping

Leaflet - overlapping markers while change event from radio button


I'm currently working on a ionic 4 and angular project with leaflet for display weather forecast on map .while to changing event in radio-group to change weather on map like wind , rain ..etc , l have overlapping markers on map .

gif image

enter image description here

How can i clear all markers while changing data to display new data ?

Code

 leafletMap() {
    // In setView add latLng and zoom
    this.map = new Map('mapId').setView([33, 44], 6);
    tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
      minZoom: 5,
      maxZoom: 6
    }).addTo(this.map);

    this.getData(event)

  } 

// markers 

  async getData(event) {
    console.log(event);

  if (event.detail.value="weather") {

  this.http.get("xxxxxxxx)
    .subscribe(data => {
      let f = data["vt1observation"]

        new L.Marker([this.cities.duhok.lat, this.cities.duhok.lng], {
          icon: new L.DivIcon({
            className: 'my-div-icon',
            html: `<div style="width: 45px";>
        <img src="assets/icon/${f.icon}.png"/ style="width:20px;">
        <span style="color:white">${f.temperature}C</span></div>`
          })
        }).addTo(this.map);

    })

    }  else if (event.detail.value="wind") {

  this.http.get("xxxxxxxx)
    .subscribe(data => {
      let f = data["vt1observation"]

        new L.Marker([this.cities.duhok.lat, this.cities.duhok.lng], {
          icon: new L.DivIcon({
            className: 'my-div-icon',
            html: `<div style="width: 45px";>
        <img src="assets/icon/${f.icon}.png"/ style="width:20px;">
        <span style="color:white">${f.wind}</span></div>`
          })
        }).addTo(this.map);

    })

Html

      <ion-item>
        <ion-label>forecast</ion-label>
        <ion-radio slot="start" value="weather" checked></ion-radio>
      </ion-item>
      <ion-item>
        <ion-label>wind</ion-label>
        <ion-radio slot="start" value="wind" ></ion-radio>
      </ion-item>

      <ion-item>
        <ion-label>humd</ion-label>
        <ion-radio slot="start" value="h"></ion-radio>
      </ion-item>

      <ion-item>
        <ion-label>rain</ion-label>
        <ion-radio slot="start" value="rain"></ion-radio>
      </ion-item>
    </ion-radio-group>
  </ion-list>

Solution

  • Instead of adding all markers directly on the map, you can add the markers on a separate layer, add your markers to a layerGroup and add the layerGroup to the map. You can remove the markers using clearLayers() method.

    var markers = L.layerGroup([marker1, marker2]).addTo(map);
    markers.clearLayers();