Rewrite Leaflet event

2020-04-21 06:11发布

问题:

I try to rewrite the boxzoom event, like this,

map.on('boxzoomend', function(e) {
    console.log('end')
})

However, the boxzoom still zoomed and I have no idea how to stop it and just print text in console. I hope to rewrite boxzoom as the following

  1. Stop from zooming
  2. Print text in console

Can you provide correct way to rewrite the event? Thank you.

回答1:

The zooming is not performed in the boxzoomend event, but rather in the BoxZoom handler. Let me quote the Leaflet source code from src/map/handler/Map.BoxZoom.js:

_onMouseUp: function (e) {

    ...

    this._map
        .fitBounds(bounds)
        .fire('boxzoomend', {boxZoomBounds: bounds});
},

A better way to achieve the functionality you want is to create a new handler that extends the BoxZoom handler, modifying the methods that you need.

I recommend that you read the Leaflet tutorials, specially the ones on creating Leaflet plugins before doing this.

The idea is to extend the BoxZoom handler:

L.Map.BoxPrinter = L.Map.BoxZoom.extend({

...modifying the _onMouseUp method...

    _onMouseUp: function (e) {

...so that instead of zooming, it just prints things:

        ...
        console.log(bounds);
        this._map.fire('boxzoomend', {boxZoomBounds: bounds});
   }
}

And as the tutorial explains, hook the handler and provide some map options for it:

L.Map.mergeOptions({boxPrinter: true});
L.Map.addInitHook('addHandler', 'boxPrinter', L.Map.BoxPrinter);

While we're at it, disable the default BoxZoom handler for all map instances by default:

L.Map.mergeOptions({boxZoom: false});

The whole thing would look like in this working example.