How to extend "onAdd" method (for Leaflet-draw)?

181 views
Skip to first unread message

ahalota

unread,
Apr 28, 2017, 12:02:25 PM4/28/17
to Leaflet
I'm trying to extend the Leaflet-draw plugin to include two extra buttons. 

I do not need to make changes to initialize(), which offers the addInitHook() function, but I do want to make a change to onAdd(), which is where Leaflet-draw creates its toolbar.

Is there something such as addInitHook(), but for other methods? I have tried redefining the onAdd() function, but then don't know how to access the original one in order to run all of those things first.

My solution now has created a subclass and simply extends() the L.Control.Draw class, but I really would prefer to have it simply add functionality to the regular onAdd() instead of forcing creating of a new class. This is because I have several extensions I am writing and I'd like each to be able to stand-alone update the L.Control.Draw without having to use a new class name (so if I add a button in Extension A, I can later use Extension B to add a second button without them having to know about each other).

Here's a snippet of the code I have right now. It works, but isn't quite what I want:

L.Control.DrawPlus = L.Control.Draw.extend({
initialize: function(options) {
        L.setOptions(this, options);
        
        L.Control.Draw.prototype.initialize.call(this, options);
    },
    
onAdd: function(map) {
var container = L.Control.Draw.prototype.onAdd.call(this,map);
var drawContainer = container.getElementsByClassName('leaflet-draw-toolbar-top')[0];
if (this.options.draw.shapefile == true){
this._addShapefileButton(drawContainer);
}

        return container;
    },

       _addShapeFileButton: function(drawContainer) { /*code to add div to toolbar*/ }
});


Reply all
Reply to author
Forward
0 new messages