Leaflet How to set center map when click marker

The example that you're following illustrates how to interact with markers by clicking on links outside of the map, and the function that you're editing is only called when you click on one of those links. It will not affect the behavior of clicking on the markers themselves.

If you replace new L.LatLng(position) with position in your edited function, clicking on the links will cause the map to center on the associated marker, but your question is about how to get the same behavior from clicking on the markers themselves.

To do that, you can create a function to be called when a marker is clicked:

function clickZoom(e) {
    map.setView(e.target.getLatLng(),5);
}

and then attach a click event listener to each marker by appending .on('click', clickZoom) when you create the layer, for example:

var marker1 = L.marker([51.497, -0.09], {
  title: "marker_1"
}).addTo(map).bindPopup("Marker 1").on('click', clickZoom);

Here is an updated fiddle showing all this at work:

http://jsfiddle.net/ZkC5M/221/


panTo() should work too:

marker.addEventListener("click", function (e){
  map.panTo(this.getLatLng());
});

for your example, it looks like this:

for(i = 0; i < markers.length; i++){
    markers[i].addEventListener("click", function(e){
        map.panTo(this.getLatLng());
    });
}

Tags:

Leaflet