Leaflet switching tabs Map container is already initialized

import { Component,ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import leaflet from 'leaflet';


@Component({
  selector: 'page-map',
  templateUrl: 'map.html'
})
export class MapPage {

  @ViewChild('map') mapContainer: ElementRef;
  map: any;

  constructor(public navCtrl: NavController) {


  }

  ionViewDidEnter() {
    this.loadmap();
  }
  loadmap() {

    this.map = leaflet.map("map").fitWorld();
    leaflet.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attributions: 'www.tphangout.com',
      maxZoom: 18
    }).addTo(this.map);
    this.map.locate({
        setView: true,
        maxZoom: 10
      }).on('locationfound', (e) => {
        let markerGroup = leaflet.featureGroup();
      let marker: any = leaflet.marker([e.latitude, e.longitude]).on('click', () => {
        marker.bindPopup("selam").openPopup();
      })
      markerGroup.addLayer(marker);
      this.map.addLayer(markerGroup);
      }).on('locationerror', (err) => {
        alert(err.message);
    })

  }
  ionViewCanLeave(){
document.getElementById("map").outerHTML = "";
}

}

On first run map works great.but after switching tabs and going back to map tab,i have map container is already initialized error.tried ionviewcanleave to make map html empty but seems like its not working.

thanks.

1 Like

still active
still active
still active

Hi,

What you can try is to remove the map before initialising it or when you leave the page:

if(this.map) {
  this.map.remove();
}
1 Like

Thanks i solved the problem with changing didload to didenter

2 Likes

Yes, Sir!! This made the magic happen.

ionViewDidEnter() {
this.loadmap();
}

Runs when the page has fully entered and is now the active page. This event will fire, whether it was the first load or a cached page.