Home > OS >  Leaflet - Map container is already initialized on page change
Leaflet - Map container is already initialized on page change

Time:11-16

I am developing an app with angular I have integrated a complement that uses Leaflet to show a map with marks on specific points.

As I've said, I developed a component to reuse on different pages. But when I change between pages that use this component, it returns me the error:

ERROR Error: Map container is already initialized.

This is my code:

HTML:

<div id="mapDetails"></div>

TS:

export class MapDetailsComponent implements AfterViewInit {

  @Input() item!: SiteDetail;
  @Output() emitOptionSelected: EventEmitter<string> = new EventEmitter();

  public map: any;

  private initMap(): void {
    console.log(this.map);
    this.map = L.map('mapDetails', {
      center: [40.4379543,-3.6795367],
      zoom: 6
    });

    const tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      minZoom: 6,
      attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    });

    tiles.addTo(this.map);
  };

  constructor() { }

  ngOnInit(): void {
    this.initMap();
  }

  ngAfterViewInit(): void {
    this.loadSites();
  }

  loadSites() {
    if(this.item) this.map.setView([this.item.latitude, this.item.longitude], 15);
    L.marker([parseFloat(this.item.latitude), parseFloat(this.item.longitude)], {alt: this.item.siteId}).addTo(this.map).bindTooltip(this.item.address1)
  }
}

I have tried everything I have found in similar issues, but nothing worked for me. For example, I don't understand why the console log in the first line of the initMap() function, is returning me undefined and instead, the L.map() function is returning me the error that the map has already existed...

Looking forward to helping

CodePudding user response:

please try this solution

change html <div id="mapDetails" #leafletMap></div> change ts file

@ViewChild('leafletMap')
private mapElement: ElementRef;

    this.map = L.map(this.mapElement.nativeElement, {
          center: [40.4379543, -3.6795367],
          zoom: 6,
        });

https://stackblitz.com/edit/child-component-8ygndy

  • Related