Problem with multiple Leaflet/MapBox maps in one Ionic app


#1

Having some difficulty in working out the best way to structure my app which has multiple Leaflet+MapBox maps on a few different views.

In particular, I have one view/controller that can be called from 3 different tabs on my app.

I just use the following line at the top of each of my controllers:

$scope.map = L.map('myMapDiv');

For each view/controller, I have a different map <DIV> name, i.e.

$scope.map = L.map('mapDivOne');  // Controller 1

$scope.map = L.map('mapDivTwo'); // Controller 2

etc. to prevent name collisions with the container.

The problem is, on the view that can be called from multiple tabs, if I have the view open on the first tab, then navigate to the second tab and open the same view there, I get the old 'Map container is already initialized' error being thrown and the view not being loaded.

I even tried:

if (!$scope.map) {
  $scope.map = L.map('commonMap');
}

which seems to work the first few times, then I get the error thrown again. (Probably when the cache expires and the view is re-initialised?).

I thought about initialising the maps at the start of the app after deviceReady(), but that is not possible as the views with the appropriate <DIV>s are not loaded at that point, so we cannot initialise the containers there.

Any suggestions on how to circumvent this problem?

Thanks.


#2

Unique ID’s was the key for me. I was having this issue in a view where I was loading different orders. So I included the order id in the div id like so:

<div id="map{{order_id}}"> </div>

And then in my controller:

$scope.map = L.map('map'+order_id);

You might also try checking and remove the map before initializing:

   if ($scope.map){
     $scope.map.remove();
    }

Hope that gives you some ideas!


#3

I’ve got this problem, and have assigned the divs unique id to the div in a *ngFor loop:

<div id="map{{id}}" class="map" style="width: 100%; height: 100%"></div>

In the controller I have the following in the constructor:

map = L.map('map'+id)

But getting the following error “Map container not found”.


#4

I’ve got the same problem.

Do you find a solution ?


#5

Not sure if you are still having the issue, but most likely the issue is that you are running this in your constructor. Need to run this after the component mounts. Try $ionicView.afterEnter