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):

To get markers like this first of all copy the Leaflet.js default marker image, which in 0.7.3 is here -> . 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:

	background-image: url("images/number-marker-icon.png");

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.


Unwanted whitespace in unordered lists using Internet Explorer

I had a drop-down menu which try as I might would not remove the whitespace from between the list item elements for IE. It turns out this is a bug with IE. The solution I eventually found was for IE only which was annoying. You simply need to set the the following style, either in your css sheet or directly:

      margin-top: -3px;

Of course you may find that you need to set margin-left instead, depending on your whitespace.

I found that this issue only seemed to occur if I had more than one child element of my li tag, but whether that is the actual cause who knows? Could be anything with Internet Explorer!

If you don’t specifically target IE then the menu/list will appear squashed in the other browsers. As I was generating this menu via an MVC HtmlHelper I was simply able to target IE directly using the UserAgent property in C#:

HtmlTextWriter writer = new HtmlTextWriter(html.ViewContext.HttpContext.Response.Output);


if (HttpContext.Current.Request.UserAgent.Contains("MSIE") == true) //HACK: Lovely IE hack
        writer.AddAttribute(HtmlTextWriterAttribute.Style, "margin-top:-3px");

Of course if you are not generating via a helper you could also use HTML directives such as:

<!--[if IE 8]>

which is ugly, but a more robust way of doing it than CSS ‘hacks’, which I am not going to discuss here as it might give you bad ideas. 🙂