[GIS] Leaflet: Map focus issue after enabling a custom ZoomToArea control in Firefox

javascriptleaflet

I'm trying to add a Zoom-to-Area control to Leaflet by extending the built in Control.Zoom plugin, but I'm fighting some "map-loses-focus" issue that affects only Firefox.

The function works as I intend in both Google Chrome and IE–once you click on the tool to enable, on mousedown you start drawing a rectangle, then on mouseup the action completes and the map zooms to the bounds of whatever rectangle you've drawn.

However in Firefox, after clicking/enabling the control, on mousedown it's like the map didn't have focus yet, and the dragging action (growing the rectangle) basically grabs a tile and just drags it around in the browser ..then when you mouseup the result is all "janked", it releases the dragging tile, still zooms to some portion of your rectangle, and fails to cleanup the rectangle in the map. BUT ..if you immediately do another zoom, it works as I would expect.

I have tried to programmatically force focus onto the map using two tricks, including one described here, but they don't solve the problem:

    // Prevent panning while drawing the zoom-to-area box.
    this._map.dragging.disable();

    // Try to return focus back to the map, necessary for FireFox.
    // 1..        
    if (this._map) {
        this._map.getContainer().focus();
    }
    // 2..
    document.getElementById('map-canvas').focus();

I created a fiddle (same link as above) so you can see the complete code and compare the behavior in different browsers. To spot it quickly, I put my code extending the Zoom plugin between two comments:

    // start added
    //
       .. so my stuff would be here

    // end added
    //

I believe my _zoomToArea: function is where a work-around should likely appear.

Does anyone have a trick to prevent this unwanted behavior in FireFox?

Best Answer

It seems one solution is to prevent this dragging issue upfront, at the document level, rather than retroactively treat the symptom and push focus back to the Leaflet map element/object using javascript..

It finally occurred to me to google "javascript firefox disable image drag", and that lead me to a generic solution over at SO.

If you're looking for a raw javascript solution, plant this little gatekeeper somewhere near the top of your initializing code:

document.ondragstart = function() { return false; };

Or alternatively, if you prefer a JQuery solution, use this:

$(document).on("dragstart", function() {
     return false;
});

With respect to my plugin, I added the override as the first line of code.

It works beautifully, and it didn't seem to break any other functionality. However I'm unclear why this is necessary for Firefox while the other browsers are unaffected by it.