Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Safely Remove Control #685

Merged
merged 2 commits into from
Apr 1, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 27 additions & 16 deletions src/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,14 @@ const Constants = require('./constants');
module.exports = function(ctx) {

let controlContainer = null;
let mapLoadedInterval = null;

const setup = {
onRemove: function() {
// Stop connect attempt in the event that control is removed before map is loaded
ctx.map.off('load', setup.connect);
clearInterval(mapLoadedInterval);

setup.removeLayers();
ctx.store.restoreMapConfig();
ctx.ui.removeButtons();
Expand All @@ -22,6 +27,13 @@ module.exports = function(ctx) {

return this;
},
connect: function() {
ctx.map.off('load', setup.connect);
clearInterval(mapLoadedInterval);
setup.addLayers();
ctx.store.storeMapConfig();
ctx.events.addEventListeners();
},
onAdd: function(map) {
ctx.map = map;
ctx.events = events(ctx);
Expand All @@ -40,21 +52,11 @@ module.exports = function(ctx) {
map.dragPan.enable();
}

let intervalId = null;

const connect = () => {
map.off('load', connect);
clearInterval(intervalId);
setup.addLayers();
ctx.store.storeMapConfig();
ctx.events.addEventListeners();
};

if (map.loaded()) {
connect();
setup.connect();
} else {
map.on('load', connect);
intervalId = setInterval(() => { if (map.loaded()) connect(); }, 16);
map.on('load', setup.connect);
mapLoadedInterval = setInterval(() => { if (map.loaded()) setup.connect(); }, 16);
}

ctx.events.start();
Expand Down Expand Up @@ -85,13 +87,22 @@ module.exports = function(ctx) {

ctx.store.render();
},
// Check for layers and sources before attempting to remove
// If user adds draw control and removes it before the map is loaded, layers and sources will be missing
removeLayers: function() {
ctx.options.styles.forEach(style => {
ctx.map.removeLayer(style.id);
if (ctx.map.getLayer(style.id)) {
ctx.map.removeLayer(style.id);
}
});

ctx.map.removeSource(Constants.sources.COLD);
ctx.map.removeSource(Constants.sources.HOT);
if (ctx.map.getSource(Constants.sources.COLD)) {
ctx.map.removeSource(Constants.sources.COLD);
}

if (ctx.map.getSource(Constants.sources.HOT)) {
ctx.map.removeSource(Constants.sources.HOT);
}
}
};

Expand Down