Sunday, 26 January 2014

Adding a marker to a leaflet.js map

The following post is a portion of the Leaflet Tips and Tricks book which is free to download. To use this post in context, consider it with the others in this blog or just download the the book as a pdf / epub or mobi .
----------------------------------------------------------


At some stage we will most likely want to add a marker to our map to pinpoint something. Leaflet makes the process nice and easy by including a marker function with several options;
In its most simple form the following is the full code to show a map with a marker;
<!DOCTYPE html>
<html>
<head>
    <title>Marker Leaflet Map</title>
    <meta charset="utf-8" />
    <link 
        rel="stylesheet" 
        href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"
    />
</head>
<body>
    <div id="map" style="width: 600px; height: 400px"></div>

    <script
        src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js">
    </script>

    <script>
        var map = L.map('map').setView([-41.2858, 174.78682], 14);
        mapLink = 
            '<a href="http://openstreetmap.org">OpenStreetMap</a>';
        L.tileLayer(
            'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: 'Map data &copy; ' + mapLink,
            maxZoom: 18,
            }).addTo(map);
        var marker = L.marker([-41.29042, 174.78219])
            .addTo(map);
        
    </script>
</body>
</html>
The only difference between this code and the simple map code is the addition of a single line at the bottom of the JavaScript portion;
        var marker = L.marker([-41.29042, 174.78219])
            .addTo(map);
Here we are declaring a variable with the L.marker method at a point of latitude -41.29042 and longitude 174.78219. Then we simply add that to our map by adding .addTo(map).
And here’s our map complete with marker…
Map with marker

Adding a popup to our marker

Adding a marker couldn’t be any easier, but it’s also not terribly informative in this context. After all, we have no information on what our marker is pointing to. However we can add this context in the form of a popup which is a small text bubble associated with the marker. To do this the code for our marker should look like this;
        var marker = L.marker([-41.29042, 174.78219])
            .addTo(map)
            .bindPopup("<b>Te Papa</b><br>Museum of New Zealand.")
            .openPopup();
Here our additional lines bind a popup to our marker using .bindPopup with the text<b>Te Papa</b><br>Museum of New Zealand. (where the <b> tags will make the text bold and the <br> tag will insert a line break). Then we open the popup with .openPopup().
The end result is…
Map with marker
But wait! The coolness doesn't end there. You can click on the marker and the popup will alternately disappear and return. If you omit the .openPopup() portion the popup won’t be open when your map loads, but if you click on the marker it will open up.

Marker options

As well as the standard marker functions shown thus far there are several options that can be utilised when displaying a marker. These are enabled by including an array of the appropriate options and their desired values in a section contained in curly braces after the latitude, longitude declaration. Below there is some sample code for the marker function with three different options demonstrating use for a boolean value (true / false) a string and a number.
    var marker = L.marker([-41.29042, 174.78219],
        {option1: true,                 // a boolean value
        option2: 'a string lives here', // a string
        option3: 1234}                  // a number
        )
       .addTo(map);
DRAG A MARKER
The draggable option is a boolean which is set to false by default, but when set to true, the marker can be repositioned by clicking on it with the mouse and moving it.
The following is a code example;
    var marker = L.marker([-41.29042, 174.78219],
        {draggable: true}
        )
       .addTo(map);
ADD A TITLE TO A MARKER
The title option is a string which will be displayed in a small rectangle beside the pointer when a users mouse is hovered over the marker.
The following is a code example;
    var marker = L.marker([-41.29042, 174.78219],
        {title: 'Hover Text'}
        )
       .addTo(map);
And this is what it looks like…
Marker with a title as hover text
ADJUST THE MARKERS TRANSPARENCY
The opacity option will vary the transparency of the marker from 0 (transparent) to 1 (opaque).
The following is a code example;
    var marker = L.marker([-41.29042, 174.78219],
        {opacity: 0.5}
        )
       .addTo(map);
And this is what it looks like…
Semi transparent marker
The full code of a live example of a map incorporating a marker with a popup, draggability, a title and opacity are available online at bl.ocks.org or GitHub. A copy is also in the appendices and a copy of all the files that appear in the book can be downloaded (in a zip file) when you download the book from Leanpub.

The description above (and heaps of other stuff) is in the Leaflet Tips and Tricks book that can be downloaded for free (or donate if you really want to :-)).

No comments:

Post a Comment