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

1
2
3
4
5
6
7
8
9
10
11
12
13
.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 */
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
var icon = L.divIcon({
iconSize: [31, 27],
iconAnchor: [13.5, 13.5],
popupAnchor: [0, -11],
className: 'rotated-markerdiv'
})
L.esri.featureLayer({
url: 'https://services.arcgis.com/rOo16HdIMeOBI4Mb/arcgis/rest/services/Trimet_Transit_Stops/FeatureServer/0',
pointToLayer: function (geojson, latlng) {
icon.options.html =
'<div class="rotate-' + geojson.properties.direction.toLowerCase() + '">'
+ '<img src="http://esri.github.io/esri-leaflet/img/bus-stop-north.png" />'
+ '</div>';
return L.marker(latlng, {
icon: icon
});
},
}).addTo(map);

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

1
2
3
4
5
6
7
8
9
10
11
12
.generate-rotate-rules(359);
.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.