Deconstructing an Open Layers 3 map
Asked Answered
M

1

12

So, I am using Open Layers 3 with Ember.js to make a dashboard, and I've made the map load dynamically but I want it do be destroyed when I leave the route, the only thing I found was map.destroy() but its for an old version of the API and there don't seem to be one in the new version.

I used the chrome debugger after going to the map page a couple of times and found that I had 29 ol.Map objects.

This is what I have so far

App.MapView = Ember.View.extend({
  map: null,
  didInsertElement: function() {
    this.map = new ol.Map({
      target: 'map',
      layers: [
        new ol.layer.Tile({
          source: new ol.source.MapQuest({layer: 'sat'})
        })
      ],
      view: new ol.View({
        center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'),
        zoom: 4
      })
    });
  },
  willDestroyElement: function() {
    // destroy this.map
  }
});

I cant find anything in the docs about removing maps.

Thanks in advance.

Murielmurielle answered 23/9, 2014 at 12:38 Comment(1)
Why not use map.dispose() ?Holter
C
26

You should try to do something like this:

App.MapView = Ember.View.extend({
  // if you are not using Ember.get/set you'd better make this "private"
  _map: null,
  didInsertElement: function() {
    this._map = new ol.Map(...);
  },
  willDestroyElement: function() {
    this._map.setTarget(null);
    this._map = null;
  }
});

It detach the map from its element and allows correct garbage collection. Don't forget to remove any other references to the map object too if any.

Cockoftherock answered 23/9, 2014 at 13:57 Comment(2)
Imagine I have a dropdown box that allows you to change between "Map" objects which contain totally different layers, vector sources, features etc. When I change to Map2 I want everything from Map1 to be completely destroyed. Is setTarget(null) the way to go?Lackaday
I think you'd have to destroy all one by one. BUT that's a long time I did not use open layers map AND it is another question; so I suggest you to ask your question as a new one instead of a comment hereCockoftherock

© 2022 - 2024 — McMap. All rights reserved.