What is the Proper Way to Destroy a Map Instance?

JavascriptGoogle Maps-Api-3

Javascript Problem Overview


I recently developed an html5 mobile application. The application was a single page where navigation hash change events replaced the entire DOM. One section of the application was a Google Map using API v3. Before the map div is removed from the DOM, I want to remove any event handlers/listeners and free up as much memory as possible as the user may not return to that section again.

What is the best way to destroy a map instance?

Javascript Solutions


Solution 1 - Javascript

I'm adding a second answer on this question, because I don't want to remove the back and forth we had via follow-up comments on my previous answer.

But I recently came across some information that directly addresses your question and so I wanted to share. I don't know if you are aware of this, but during the Google Maps API Office Hours May 9 2012 Video, Chris Broadfoot and Luke Mahe from Google discussed this very question from stackoverflow. If you set the video playback to 12:50, that is the section where they discuss your question.

Essentially, they admit that it is a bug, but also add that they don't really support use cases that involve creating/destroying successive map instances. They strongly recommend creating a single instance of the map and reusing it in any scenario of this kind. They also talk about setting the map to null, and explicitly removing event listeners. You expressed concerns about the event listeners, I thought just setting the map to null would suffice, but it looks like your concerns are valid, because they mention event listeners specifically. They also recommended completely removing the DIV that holds the map as well.

At any rate, just wanted to pass this along and make sure it is included in the stackoverflow discussion and hope it helps you and others-

Solution 2 - Javascript

The official answer is you don't. Map instances in a single page application should be reused and not destroyed then recreated.

For some single page applications, this may mean re-architecting the solution such that once a map is created it may be hidden or disconnected from the DOM, but it is never destroyed/recreated.

Solution 3 - Javascript

Since apparently you cannot really destroy map instances, a way to reduce this problem if

  • you need to show several maps at once on a website
  • the number of maps may change with user interaction
  • the maps need to be hidden and re-shown together with other components (ie they do not appear in a fixed position in the DOM)

is keeping a pool of map instances. The pool keeps tracks of instances being used, and when it is requested a new instance, it checks if any of the available map instances is free: if it is, it will return an existing one, if it is not, it will create a new map instance and return it, adding it to the pool. This way you will only have a maximum number of instances equal to the maximum number of maps you ever show simultaneously on screen. I'm using this code (it requires jQuery):

var mapInstancesPool = {
 pool: [],
 used: 0,
 getInstance: function(options){
	if(mapInstancesPool.used >= mapInstancesPool.pool.length){
		mapInstancesPool.used++;
		mapInstancesPool.pool.push (mapInstancesPool.createNewInstance(options));
	} else { 
		mapInstancesPool.used++;
	}
	return mapInstancesPool.pool[mapInstancesPool.used-1];
 },
 reset: function(){
	mapInstancesPool.used = 0;
 },
 createNewInstance: function(options){
	var div = $("<div></div>").addClass("myDivClassHereForStyling");
	var map =   new google.maps.Map(div[0], options);
	return {
		map: map,
		div: div
	}
 }
}

You pass it the starting map options (as per the second argument of google.maps.Map's constructor), and it returns both the map instance (on which you can call functions pertaining to google.maps.Map), and the container

, which you can style using the class "myDivClassHereForStyling", and you can dinamically append to the DOM. If you need to reset the system, you can use mapInstancesPool.reset(). It will reset the counter to 0, while keeping all existing instances in the pool for reuse. In my application I needed to remove all maps at once and create a new set of maps, so there's no function to recycle a specific map instance: your mileage may vary. To remove the maps from the screen, I use jQuery's detach, which doesn't destroy the map's container
.

By using this system, and using

google.maps.event.clearInstanceListeners(window);
google.maps.event.clearInstanceListeners(document);

and running

google.maps.event.clearInstanceListeners(divReference[0]);
divReference.detach()

(where divReference is the div's jQuery object returned from the Instance Pool) on every div I'm removing, I managed to keep Chrome's memory usage more or less stable, as opposed to it increasing every time I delete maps and add new ones.

Solution 4 - Javascript

I would have suggested removing the content of the map div and using delete on the variable holding the reference to the map, and probably explicitly deleteing any event listeners.

There is an acknowledged bug, though, and this may not work.

Solution 5 - Javascript

As google doesnt provide gunload() for api v3 better use iframe in html and assign map.html as a source to this iframe. after use make src as null. That will definitely free the memory consumed by map.

Solution 6 - Javascript

When you remove the div, that removes the display panel and the map will disappear. To remove the map instance, just make sure that your reference to the map is set to null and that any references to other parts of the map are set to null. At that point, JavaScript garbage collection will take care of cleaning up, as described in: https://stackoverflow.com/q/4324133/1314132.

Solution 7 - Javascript

I guess you're talking about addEventListener. When you remove the DOM elements, some browsers leak these events and doesn't remove them. This is why jQuery does several things when removing an element:

  • It removes the events when it can using removeEventListener. That means it's keeping an array with the event listeners it added on this element.
  • It deletes the attributes about events (onclick, onblur, etc) using delete on the DOM element when addEventListener is not available (still, it has an array where it stores the events added).
  • It sets the element to null to avoid IE 6/7/8 memory leaks.
  • It then removes the element.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChad KillingsworthView Question on Stackoverflow
Solution 1 - JavascriptSean MickeyView Answer on Stackoverflow
Solution 2 - JavascriptChad KillingsworthView Answer on Stackoverflow
Solution 3 - JavascriptPaolo MioniView Answer on Stackoverflow
Solution 4 - JavascriptAndrew LeachView Answer on Stackoverflow
Solution 5 - JavascriptkumarView Answer on Stackoverflow
Solution 6 - JavascriptSean MickeyView Answer on Stackoverflow
Solution 7 - JavascriptFlorian MargaineView Answer on Stackoverflow