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