2016-08-08 69 views
1

我在我的Ionic 2應用程序中使用了Leaflet。第一次運行應用程序時。 Everyhting很好。但是,如果我轉到另一頁並返回到地圖,我會看到以下例外:LeafletJS:地圖容器已經初始化

例外:錯誤:未捕獲(承諾中):EXCEPTION:構建/頁面/地圖/ map.html中的錯誤:12:18 原始異常:錯誤:地圖容器已經初始化。 ORIGINAL STACKTRACE: 錯誤:地圖容器已經初始化。

返回此頁面時,私有變量映射爲null。檢查這個變量beeing空沒有任何影響,因爲我認爲這個問題是新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); 
    } 

} 
+0

什麼是你的組件相關聯的模板的代碼?你的'mainmap'位於哪裏?在你的組件模板中?謝謝! –

回答

2

if(this.map == null)條件在ngOnInit()總是true,因爲當你實例化一個新MainMapComponent,新的實例將獲得自己的全新this.map,因此未分配(即undefined)呢。

這是從什麼可以發生在你"mainmap"的div容器完全不同。

爲了更貼近您的問題描述,在離開地圖導航時,您的"mainmap" div容器仍然保留地圖。當回到你的頁面時,它看起來像你的應用程序實例化一個新的MainMapComponent實例,它有一個新的(尚未分配的)this.map,因此它嘗試初始化一個新的地圖"mainmap" div容器。這是造成錯誤的原因。

你可以嘗試使用this.map.remove()當你MainMapComponent實例將被破壞,從而使"mainmap" DIV狀態處於看齊的MainMapComponent實例的存在(或沒有)。但是,如果由於任何原因您同時擁有多個MainMapComponent實例,那麼這並不能解決您的問題。


更新:

至於最後提到的問題,請參閱Initializing leaflet map in angular2 component after DOM object exists

+0

我沒有實例化多個MainMapComponents,但在onInit()它再次調用同一個div上的新L.Map()。我不知道如何檢查,如果一個DOM元素已經用地圖初始化了。 – rakete

+0

只需查找可能已被另一個Leaflet實例化添加的子節點... – ghybs

+0

不,我確定它是我的第一個ngOnInit()的實例。但如何獲得回扣到我的this.map var? – rakete