Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet How to set center map when click marker

Tags:

leaflet

I follow this example http://jsfiddle.net/abenrob/ZkC5M/ , When i click marker I want map pan to marker and set position center screen my code is below but when i click map.setView(new L.LatLng(position), 5); is not working.

 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,

like image 232
droidstack Avatar asked Feb 02 '16 09:02

droidstack


People also ask

How do I create a pop up map in Leaflet?

Use the addPopups() function to add standalone popup to the map. A common use for popups is to have them appear when markers or shapes are clicked. Marker and shape functions in the Leaflet package take a popup argument, where you can pass in HTML to easily attach a simple popup.

How many markers can Leaflet handle?

The Clusterer can handle 10,000 or even 50,000 markers (in chrome).

Why is map not showing in Leaflet?

There are a number of reasons why your map might not be displaying: You have an error in your JavaScript (most likely) - use whichever debugging tool is provided with your browser to verify. you are using Internet Explorer and you have Compatibility mode ON....


1 Answers

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/

like image 140
nathansnider Avatar answered Dec 26 '22 20:12

nathansnider