Simple numbered markers with Leaflet.js

I thought I’d look up how to create markers that are numbered with the excellent Leaflet.js. Perhaps surprisingly there is no built in method, but looking round the Web there are a few suggested ways of doing it. These all seemed rather over-engineered though so I decided to engage brain rather than just blindly copying. The following method works, and is a lot less complicated than anything else I’ve seen out there.

I wanted to achieve this (yes I know grey is not a good choice in this case, but it is what the user wanted):
map

To get markers like this first of all copy the Leaflet.js default marker image, which in 0.7.3 is here -> http://cdn.leafletjs.com/leaflet-0.7.3/images/marker-icon.png . I simply modified this using Paint.Net to be solid grey. Put the final image into your website/application.

Create a CSS class like this, obviously substituting your image path/name and font colour:

.number-icon
{
	background-image: url("images/number-marker-icon.png");
	text-align:center;
	color:White;	
}

Then when creating your marker you need to add this code, putting the number in the ‘html’ parameter:

      var numberIcon = L.divIcon({
            className: "number-icon",
            iconSize: [25, 41],
            iconAnchor: [10, 44],
            popupAnchor: [3, -40],
            html: variable_containing_the_number        
      });

      var marker = new L.marker([lat, long],
                            {
                                
                                icon: numberIcon
                                
                            });

And that’s all there is to it. Not quite sure why there are so many other elaborate methods out there, but maybe they work for use cases other than the one I had too.

Advertisements

2 Responses to Simple numbered markers with Leaflet.js

  1. is the number in the markers dynamic sir?

    • Andrew Jerrison says:

      Yes, just replace the ‘variable_containing_the_number’ string with whatever text you want to appear in the marker. It could be a variable that you increment, or just some static text.

Leave a Reply

Please log in using one of these methods to post your comment:

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

%d bloggers like this: