Reputation: 129
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,
Upvotes: 11
Views: 45351
Reputation: 1444
In practice, the panTo()
and setView()
behave differently.
To load the map with the view, use setView()
when creating the map object:
var map = L.map('map').setView([lat, long], 5);
To watch the map move / pan, use with one of these after creating the map object:
map.setView([lat, long], 5);
or:
map.panTo([lat, long]);
Note: setView()
allows you to set the Zoom, while panTo()
only supports position.
Upvotes: 1
Reputation: 863
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());
});
}
Upvotes: 10
Reputation: 2873
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/
Upvotes: 28