So this is one of the top hits in Google for styling Leaflet Icon, but it didn't have a solution that worked without third parties, and I was having this problem in React as we needed dynamic colours for our routes and icons.
The solution I came up with was to use Leaflet.DivIcon html
attribute, it allows you to pass a string which is evaluated into a DOM element.
So for example I created a marker style follows:
const myCustomColour = '#583470'
const markerHtmlStyles = `
background-color: ${myCustomColour};
width: 3rem;
height: 3rem;
display: block;
left: -1.5rem;
top: -1.5rem;
position: relative;
border-radius: 3rem 3rem 0;
transform: rotate(45deg);
border: 1px solid #FFFFFF`
const icon = Leaflet.divIcon({
className: "my-custom-pin",
iconAnchor: [0, 24],
labelAnchor: [-6, 0],
popupAnchor: [0, -36],
html: `<span style="${markerHtmlStyles}" />`
})
Change background-color
in markerHtmlStyles
to your custom colour and you're good to go.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…