0

I initialized a map by importing leaflet Typescript namespace via TSD, but I have some problems with the map being reinitialized each time I instantiate a new component (that contains the map). Here's the code of the component :

    import { Component, Input, OnInit} from '@angular/core';

    import { MapDetail } from './map';

    @Component({
        selector:'map-detail',
        templateUrl: 'views/map.html'
    })
    export class MapDetailComponent implements OnInit {
        @Input()   map: MapDetail;

        ngOnInit(): void {

            var div = document.getElementById('map');
            var mymap : L.Map = L.map(div, {
                center: L.latLng(47.137,  1.890),
                zoom: 7,    
                dragging: true,
                [More options ...]
            });

        var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?', {
                minZoom: 3,
                maxZoom: 18,
            });


            tileLayer.addTo(mymap);
        }
    }

And the HTML :

<div id="mapid"></div>

Any idea/hint is greatly appreciated.

UPDATE : The ngOnInit is called twice. I used to use a service to call it before. Now since it's a blank page it is initiating I call this component directly.

UPDATE 2 : seems like it is related to this issue https://github.com/angular/angular/issues/6782 Is there any known workaround ?

Ismail H
  • 4,226
  • 2
  • 38
  • 61

2 Answers2

2

You could simply record your div or mymap in a private member of your class, and initialize the map only if that member is undefined.

But then you may still have a problem if you have several instances of that component on your page. I am not exactly sure how Shadow DOM handles components having div's with same ID?

Or simply check first if the map container is empty or not before initializing it with Leaflet.

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • I added the HTML. The member will never be undefined since it exists. I can do some checking to see if there's content inside, but I'm not sure that it is the angular way to do it. And not sure what a Shadow DOM is. Let me look for it. – Ismail H Sep 28 '16 at 07:56
  • This solution hasn't worked for me. When I instantiate a new component, both the constructor and ngnit functions are re-run. They both say that the private member is undefined each time, so the error still occurs. – carpiediem Apr 10 '17 at 13:30
  • @carpiediem You might be interested in that one: http://stackoverflow.com/questions/42428251/initializing-leaflet-map-in-angular2-component-after-dom-object-exists/42431059#42431059 – ghybs Apr 10 '17 at 13:34
  • @ghybs Thanks a lot, I'll try it out. – carpiediem Apr 10 '17 at 13:37
  • @carpiediem Thx for the feedback, glad it helped you! Feel free to vote. – ghybs Apr 10 '17 at 13:57
0

You can also try this for map implementation: https://angular-maps.com/

Manish
  • 2,092
  • 16
  • 18