Book Image

Leaflet.js Essentials

Book Image

Leaflet.js Essentials

Overview of this book

Table of Contents (13 chapters)
Leaflet.js Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Pop ups


The last few examples introduced pop ups. A pop up provides a way to make your layers interactive or provides information to the user. The simplest way to add a pop up to a marker, polyline, or polygon is to use the bindPopup() method. This method takes the contents of the pop up as a parameter. Using the marker variable we created earlier, we bind the pop up to it with the following code:

marker.bindPopup("I am a marker");

The bindPopup() method allows you to enter HTML as the content. This is shown in the following code:

marker.bindPopup("<h1>My Marker</h1><p>This is information about the marker</p><ul><li>Info 1</li><li>Info 2</li><li>Info 3</li></ul>")

The ability to use HTML in a pop up comes in handy when you have a lot of details to add. It allows the use of images and links in pop ups. The following screenshot shows the HTML-formatted pop up added to a marker on the map:

You can also create an instance of the popup class and then assign it to multiple objects:

var mypopup = L.popup({keepInView:true,closeButton:false})
.setContent("<h1>My Marker</h1><p>This is information about the marker</p><ul><li>Info 1</li><li>Info 2</li><li>Info 3</li></ul>");
marker.bindPopup(mypopup);
marker2.bindPopup(mypopup);

In the preceding code, you create an instance of the L.popup() class and assign it to the variable mypopup. Then, you can call the bindPopup() method on marker and marker2 with mypopup as the parameter. Both markers will have the same pop up content and options.

In the last section of this chapter, you will learn how to create a function that allows you to create a pop up with options and pass the content as a parameter.