I followed this example: http://jsfiddle.net/abenrob/ZkC5M/.
When I click a marker, I want the map to pan to the marker and position it at the center of the screen. My code is below, but when I use map.setView(new L.LatLng(position), 5); it doesn't work
function markerFunction(id){
for (var i in markers){
var markerID = markers[i].options.title;
var position = markers[i].getLatLng();
if (markerID == id){
map.setView(new L.LatLng(position), 5);
markers[i].openPopup();
};
}
}
Thank you,
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: