Reputation: 4479
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 ?
Upvotes: 0
Views: 2819
Reputation: 2180
You can also try this for map implementation: https://angular-maps.com/
Upvotes: 0
Reputation: 53185
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.
Upvotes: 2