Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Leaflet.js Essentials

You're reading from   Leaflet.js Essentials Create interactive, mobile-friendly mapping applications using the incredibly light yet powerful Leaflet.js platform.

Arrow left icon
Product type Paperback
Published in Aug 2014
Publisher
ISBN-13 9781783554812
Length 180 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Events and event handlers

So far, you have created maps that display data and added a pop up that displayed when the user clicked on a marker. Now, you will learn how to handle other events and assign these events to event handler functions to process them and do something as a result.

You will first learn how to handle a map event. There are 34 events in the map class that can be subscribed to. This example will focus on the click event. To subscribe to an event, you use the event method .on(); so, for a map event, you use the map.on() method and pass the parameters as the event and function to handle the event. This is shown in the following code:

map.on('click', function(){alert("You clicked the map");});

The code tells Leaflet to send an alert pop-up box with the text You clicked the map when the user clicks on the map. In the mobile example, you created a listener that had a named function that executed foundLocation(). In the preceding code, the function was put in as a parameter. This is known as an anonymous function. The function has no name, and so, it can only be called when the user clicks on the map.

Remember e from the mobile example? If you pass e to the function, you can get the longlat value of the spot that the user clicked on, as shown in the following code:

map.on('click',function(e){
var coord=e.latlng.toString().split(',');
var lat=coord[0].split('(');
var long=coord[1].split(')');
alert("you clicked the map at LAT: "+ lat[1]+" and LONG:"+long[0])
});

The preceding code is spaced in a way that is more readable, but you can put it all on a single line. The code displays the longitude and latitude of the spot where the user clicked on the map. The second line assigns the variable coord, the value of e.latlng. The next two lines strip the latitude and longitude from the value so that you can display them clearly.

You can build on this example by adding a marker when the user clicks on the map by simply replacing the code with the following:

L.marker(e.latlng).addTo(map);

The preceding code is identical to the code in the mobile example. The difference is that in the mobile example, it was only executed when locate() was successful. In this example, it is executed every time the user clicks on the map.

In the section on markers, you created a marker that had the property draggable:true. Markers have three events that deal with dragging: dragstart, drag, and dragend. Perform the following steps to return the longitude and latitude of the marker in a pop up on dragend:

  1. Create the marker and set the draggable property to true:
    varmyMarker = L.marker([35.10418, -106.62987],{title:"MyPoint",alt:"The Big I",draggable:true}).addTo(map);
  2. Write a function to bind a pop up to the marker and call the method getLatLong():
    myMarker.bindPopup("I have been moved to: "+String(myMarker.getLatLng()));
  3. Subscribe to the event:
    myMarker.on('dragend',whereAmI);

Open the map and click on the marker. Hold down the left mouse button and drag the marker to a new location on the map. Release the left button and click on the marker again to trigger the pop up. The pop up will have the new latitude and longitude of the marker.

Custom functions

You subscribed to an event and handled it with a function. So far, you have only passed e as a parameter. In JavaScript, you can send anything you want to the function. Also, functions can be called anywhere in your code. You do not have to call them only in response to an event. In this short example, you will create a function that returns a pop up and is triggered on a call and not by an event.

First, create a marker and bind a pop up to it. For the content of the pop up, enter createPopup(Text as a parameter). Add the marker to the map as shown in the following code:

var marker1 = L.marker([35.10418, -106.62987]).addTo(map).bindPopup(createPopup("Text as a parameter"));

Create a second marker and set the content of the pop up to createPopup (Different text as a parameter):

var marker2 = L.marker([35, -106]).addTo(map).bindPopup(createPopup("Different text as a parameter"));

In the previous examples, you created a pop up by passing text or a pop-up instance. In this example, you call a function, createPopup(), with a string as a parameter, as shown in the following code:

functioncreatePopup(x){
return L.popup({keepInView:true,closeButton:false}).setContent(x);function createPopup(x){
returnL.popup({keepInView:true,closeButton:false}).setContent(x);
}

The function takes a parameter called x. In the marker, when you call the function, you pass a string. This is sent to the function and stored as x. When the pop up is created, the setContent() method is given the value of x instead of a hardcoded string. This function is useful if you have a lot of options set on your pop ups and want them all to be the same. It limits the number of times that you need to repeat the same code. Just pass the text of the pop up to the function, and you get a new pop up with the standardized formatting options. The following screenshot shows both of the pop ups generated by the custom function:

Custom functions
You have been reading a chapter from
Leaflet.js Essentials
Published in: Aug 2014
Publisher:
ISBN-13: 9781783554812
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image