破坏映射实例的正确方法是什么?

我最近开发了一个 html5移动应用程序。应用程序是一个单独的页面,其中导航散列更改事件取代了整个 DOM。应用程序的一个部分是使用 API v3的 GoogleMap。在从 DOM 中删除 map div 之前,我希望删除任何事件处理程序/侦听器,并释放尽可能多的内存,因为用户可能不会再次返回该部分。

销毁映射实例的最佳方法是什么?

74641 次浏览

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: How does garbage collection work in 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.

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.

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-

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.

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.

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.