DivIcon
Quick answer
L.divIcon builds a marker icon from an HTML string and CSS instead of image files, which removes network requests and lets you style pins with your own classes. It is the practical route for badges, counters and text labels drawn directly on a map.
L.divIcon( options ) → DivIcon
Key points
- Set className to an empty string, otherwise the default white bordered square shows.
- iconAnchor must match iconSize so the intended pixel sits on the coordinate.
- html accepts either a string or a ready DOM node as icon content.
Example
<style>
.badge {
width: 26px; height: 26px; border-radius: 50%;
background: #1f5fd0; color: #fff; font: 600 12px/26px sans-serif;
text-align: center; box-shadow: 0 0 0 3px rgba(31, 95, 208, .2);
}
.tag {
padding: 3px 8px; border-radius: 4px; white-space: nowrap;
background: #16181d; color: #fff; font: 12px/1.4 sans-serif;
}
</style>
var badge = L.divIcon({
className: '',
html: '<div class="badge">7</div>',
iconSize: [26, 26],
iconAnchor: [13, 13]
});
L.marker([39.907, 116.391], { icon: badge })
.bindPopup('当前站点 7 条告警')
.addTo(map);
var tag = L.divIcon({
className: '',
html: '<div class="tag">北京南站</div>',
iconSize: [76, 24],
iconAnchor: [38, 34],
tooltipAnchor: [0, -20]
});
Notes
- A mismatched iconAnchor shifts every marker slightly and is hard to notice at first.
- Hiding the container with display none prevents Leaflet from measuring its size.
English edition written for Atlaslog. Code is taken from the original Chinese page and runs unchanged.
Atlaslog (2026). DivIcon. https://www.jingweizhi.com/en/leaflet/api/div-icon.html (accessed 2026-11-03).