Rotated Icons with Leaflet

Demo      Source

I recently had the need to display rotated markers on a map for a project using Leaflet leaflet and Esri Leaflet. After a quick Google search I couldn’t see any standard way to do it so I thought I’d roll my own. My dataset had a bearing value which I could use to set the rotation, so I used that in combination with the L.divIcon and some CSS to get the desired result.

A bastardised version of this Styling Points sample can be seen with the effect .

The relevant code bits are

.rotated-markerdiv {
    text-align: center;
    background-color: none;
    border: none;

.rotate-north {
    transform: rotate(0);            /* CSS3 */
    -moz-transform: rotate(0);       /* Firefox */
    -webkit-transform: rotate(0);    /* Webkit */
    -o-transform: rotate(0);         /* Opera */
    -ms-transform: rotate(0);        /* IE 9 */
var icon = L.divIcon({
    iconSize: [31, 27],
    iconAnchor: [13.5, 13.5],
    popupAnchor: [0, -11],
    className: 'rotated-markerdiv'

    url: '',
    pointToLayer: function (geojson, latlng) {

        icon.options.html =
            '<div class="rotate-' + + '">'
             + '<img src="" />'
          + '</div>';

        return L.marker(latlng, {
            icon: icon

Now in that sample I am hardcoding the rotated classes since there are only 4 values, but in my real world application it could be between 0 and 359, so rather than type out that I used Less to allow me to specify the same in a much more terse manner


.generate-rotate-rules(@n, @i: 0) when (@i =< @n) {
    .rotate-@{i} {
        transform: rotate(unit(@i, deg)); /* CSS3 */
        -moz-transform: rotate(unit(@i, deg)); /* Firefox */
        -webkit-transform: rotate(unit(@i, deg)); /* Webkit */
        -o-transform: rotate(unit(@i, deg)); /* Opera */
        -ms-transform: rotate(unit(@i, deg)); /* IE 9 */
    .generate-rotate-rules(@n, (@i + 1));

If you have any feedback or suggestions, feel free to sound off in the comments.

comments powered by Disqus