Customized marker content in Leaflet

Leaflet is my favourite mapping library, and hence is always my first choice when it comes to building apps around maps.

A project I recently worked on required data to be attached to markers, which needed to be used outside the map. To achieve this, I would need to add custom options to the ones that already exist in the Marker class. I’ve put together a small and simple tutorial that would help you achieve this.

Objective: To store custom content in a leaflet marker.

Step 1: Set up a leaflet map object.

var map = L.map('map').setView([28.63278, 77.21972], 14);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }).addTo(map);

Step 2:  Create a custom class that extend the Marker class.


customMarker = L.Marker.extend({
options: {
name: '',
type: ''
}
});

Step 3:  Create a new object of this class and initialize the new custom options.


var marker = new customMarker([28.63278, 77.21972],{
clickable: true,
name: 'Connaught Place',
type: 'Neighbourhood'
}).addTo(map);

Step 4:  Your custom content has been successfully been added to the marker! Now, let’s display this content on the web page to test it. To do this, we will invoke a custom function ‘onClick’ on the ‘click’ event of the marker. In this function, we will use a bit of jQuery to display the custom content in a div with the id ‘content’.


var marker = new customMarker([28.63278, 77.21972],{
clickable: true,
name: 'Connaught Place',
type: 'Neighbourhood'
}).on('click', onClick).addTo(map);
function onClick(e) {
$('#content').html("
Name: "+this.options.name+"
Type: "+this.options.type+"
">;")
}

And you’re done! You have successfully added custom content to a marker and displayed the new content in a div!

This is the JFiddle of the code: http://jsfiddle.net/cartofy/shJ4A/

You can read more about extending Leaflet classes here.

Happy coding!

 

Advertisements

3 thoughts on “Customized marker content in Leaflet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s