angularjs - LeafletJS: Map container is already initialized -


i using leaflet in ionic 2 app. when running app first time. everyhting fine. if go page , map following exception:

exception: error: uncaught (in promise): exception: error in build/pages/map/map.html:12:18 original exception: error: map container initialized. original stacktrace: error: map container initialized.

the private variable map null when coming page. checking variable beeing null has no effect because think problem new l.map('mainmap',...

export class mainmapcomponent {    private map;    constructor(     private mapservice: mapservice,     private geocodingservice: geocodingservice) { }    ngoninit() {     console.log(this.map);     if( this.map == null ) this.initmap();   }    initmap() {     console.log('init');     if(this.map) this.map.remove();     this.map = new l.map('mainmap', {       zoomcontrol: false,       center: new l.latlng(40.731253, -73.996139),       zoom: 12,       minzoom: 4,       maxzoom: 19,       layers: [this.mapservice.basemaps.openstreetmap],       attributioncontrol: false     });     console.log(this.map);   }  } 

the if( this.map == null ) condition in ngoninit() true, since when instantiate new mainmapcomponent, new instance own brand new this.map, therefore unassigned (i.e. undefined) yet.

this totally different may have happened "mainmap" div container.

to more inline problem description, when navigating away map, "mainmap" div container still holds map. when coming page, looks app instantiates new mainmapcomponent instance, has new (unassigned yet) this.map, therefore tries initialize new map in "mainmap" div container. creates error.

you try use this.map.remove() when mainmapcomponent instance destroyed, "mainmap" div status in par existence (or not) of instance of mainmapcomponent. not solve problem if reason have more 1 instance of mainmapcomponent @ same time.


update:

as last mentioned issue, see initializing leaflet map in angular2 component after dom object exists


Comments