Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marker in leaflet, click event

var map = L.map('map'); var marker = L.marker([10.496093,-66.881935]).on('click', onClick); function onClick(e) {alert(e.latlng);} marker.addTo(map) 

When I do click in the marker, the alert message is: undefined

But if I put it in the variable map, it works! (shows latitude and longitude)

map.on('click', onClick);  

Does someone know why it doesn't work in the marker?

like image 736
Jonathan García Avatar asked Jun 04 '13 21:06

Jonathan García


People also ask

How do you put a marker on click in leaflet?

Adding a Simple MarkerStep 1 − Create a Map object by passing a <div> element (String or object) and map options (optional). Step 2 − Create a Layer object by passing the URL of the desired tile. Step 3 − Add the layer object to the map using the addLayer() method of the Map class.

How do you get marker off a leaflet map?

Layergroup allows to control all markers at once. Ok, removing the layer seems to be the solution, but the more straightforward answer to the question, how to remove a marker is the one given by @HarijsKrūtainis : marker. remove() , it worked perfectly to me.

How many markers can leaflet handle?

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

What is leaflet in JavaScript?

Leaflet is the leading open-source JavaScript library for mobile-friendly interactive maps. Weighing just about 42 KB of JS , it has all the mapping features most developers ever need. Leaflet is designed with simplicity, performance and usability in mind.


2 Answers

The accepted answer is correct. However, I needed a little bit more clarity, so in case someone else does too:

Leaflet allows events to fire on virtually anything you do on its map, in this case a marker.

So you could create a marker as suggested by the question above:

L.marker([10.496093,-66.881935]).addTo(map).on('mouseover', onClick); 

Then create the onClick function:

function onClick(e) {     alert(this.getLatLng()); } 

Now anytime you mouseover that marker it will fire an alert of the current lat/long.

However, you could use 'click', 'dblclick', etc. instead of 'mouseover' and instead of alerting lat/long you can use the body of onClick to do anything else you want:

L.marker([10.496093,-66.881935]).addTo(map).on('click', function(e) {     console.log(e.latlng); }); 

Here is the documentation: http://leafletjs.com/reference.html#events

like image 87
Chris Avatar answered Oct 16 '22 04:10

Chris


Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/

var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);  function markerOnClick(e) {   alert("hi. you clicked the marker at " + e.latlng); } 
like image 32
Timo Sperisen Avatar answered Oct 16 '22 05:10

Timo Sperisen