Leaflet, Ionic 3 and “Map container is already initialized”

When developing the new Unit app interface we decided on a map to fill the entire back of the home view. Allowing a user to see their entire surrounding area with calls and other markers. But we ran into quite a few issue where navigation would kill the map with “Map container is already initialized” error.

2018-07-01 10_23_25-Resgrid Unit

The map was being declared like this:

2018-07-01 22_07_45-● home.ts - Unit - Visual Studio Code

I tried moving the initialization to every part of the Ionic View Lifecycle events and the Angular events without fixing the issue. I implemented cleanup code and even tried clearing and recreating the DOM all without completely fixing the issue. What eventually fixed the issue was instead of passing in a string for that first map param (the id of the html element) pass in the actual element:

2018-07-01 22_08_14-● home.ts - Unit - Visual Studio Code

2018-07-01 22_07_59-home.html - Unit - Visual Studio Code

It’s important on your HTML to have the #map (or whatever you want to reference the element as inside you code). Then you can create a ViewChild in there with that name inside your controller:

2018-07-03 08_05_55-home.ts - Unit - Visual Studio Code

After that no more issues, no cleanup code needed, no hooking into multiple lifecycle events.

If you’re a First Responder or part of a Disaster Response Org, or know someone who is, check out Resgrid which is a SaaS product utilizing Microsoft Azure, providing free logistics, management and communication tools to first responder organizations like volunteer fire departments, career fire departments, EMS, search & rescue, CERT, public safety, security and disaster relief organizations.

About: Shawn Jackson

I’ve spent the last 18 years in the world of Information Technology on both the IT and Development sides of the aisle. I’m currently a Software Engineer for Paylocity. In addition to working at Paylocity, I’m also the Founder of Resgrid, a cloud services company dedicated to providing logistics and management solutions to first responder organizations, volunteer and career fire departments, EMS, ambulance services, search and rescue, public safety, HAZMAT and others.