One thing that I really like about leaflet popups is that they have the autoPan option, which means that if I select a feature programatically in my JavaScript, the map will scroll to fit it, without me having to pass the map around everywhere in my code.

Recently, we changed our spec to get rid of popups from our map. But I still want the autoPan feature! I'm tempted to create an "invisible" popup with code like this, so the popup never shows up, but is open just long enough to trigger the autopan.

layer.bindPopup('', { closeOnClick: false }) layer.on('popupopen', () => layer.closePopup())

But this seems really hacky. Does anyone know of a better way to autopan to a feature, without having a reference to the map?

2 Answers 2


Not sure if your using JQuery Autocomplete or the search plugin, so here are two examples.

Here is an example using JQuery Autocomplete to search state polygons by name: http://www.gistechsolutions.com/leaflet/DEMO/Search/SearchState.html

In the forEachFeature.... for your search layer, make the Leaflet layer ID the name to search on.

// Tagging each state poly with their name for the search control.
layer._leaflet_id = feature.properties.STATE_NAME;

Then when they select by state name (a) I fire off this function,

function polySelect(a){
    map._layers[a].fire('click');  // 'clicks' on state name from search
    var layer = map._layers[a];
    map.fitBounds(layer.getBounds());  // zooms to selected poly

For points, I used the leaflet search plugin: http://www.gistechsolutions.com/leaflet/DEMO/baseball/Baseball2.html

Here I just grab the point coordinates and use them to set the setView center point and use a fixed zoom.

var searchControl = new L.Control.Search({
    layer: bbTeam,
    propertyName: 'Name',
    marker: false,
    moveToLocation: function(latlng) {
        map.setView(latlng, 12); // set the zoom
  • This is a great answer, but I'm looking for something that doesn't require having a reference to the map to work, because I create and keep track of my features in a totally separate part of the code from where the map is stored. With a popup, just calling feature.togglePopup pans the map, without having to call any map functions
    – Teddy Ward
    Commented Jan 24, 2018 at 18:41

I ended up figuring out that if you fire an event on a layer, you can access the map and the layer's latlng from the event target

So I just added an event listener on every layer as follows:

layer.on('autoPan', (event) => { let mappedLayer = event.target let center = mappedLayer._latlng || mappedLayer.getBounds().getCenter() mappedLayer._map.panTo(center) })

This way, I didn't have to store (and pass around) a reference to the map. I could just fire an 'autoPan' event on any layer that was selected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.