[GIS] How to zoom/Pan to a Leaflet Map, such that the given point is off-center

javascriptleafletoffsetzoom

In my Leaflet Application, on some event, I want to zoom to a particular marker, and then show it's popup. I have certain other custom components on top of the map, and the Popup that appears, is hidden behind these components.

This could be resolved, if I could zoom/pan to the map, such that the given point (i.e. location of marker) is not in the center, but slightly lower.

How do I do this?

Best Answer

This has been discussed in this Issue: https://github.com/Leaflet/Leaflet/issues/859

Based on the code given there, I wrote the following two functions:

L.Map.prototype.panToOffset = function (latlng, offset, options) {
    var x = this.latLngToContainerPoint(latlng).x - offset[0]
    var y = this.latLngToContainerPoint(latlng).y - offset[1]
    var point = this.containerPointToLatLng([x, y])
    return this.setView(point, this._zoom, { pan: options })
}

L.Map.prototype.setViewOffset = function (latlng, offset, targetZoom) {
    var targetPoint = this.project(latlng, targetZoom).subtract(offset),
    targetLatLng = this.unproject(targetPoint, targetZoom);
    return this.setView(targetLatLng, targetZoom);
}

Now these functions can be called as follows:

map.panToOffset(e.target.getLatLng(),[0,100], {"animate":true});
//or if you want to zoom to
map.setViewOffset(e.target.getLatLng(),[0,100],9);
Related Question