[GIS] Autopan in Leaflet, Without a Popup

leafletpanpopup

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?

Best Answer

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
    }
});