Leaflet changing Marker color
Solution 1:
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.
Solution 2:
Bind in the icons from this site!
https://github.com/pointhi/leaflet-color-markers
Detailed how-to information included on the website.
Edit: Use the code below to add a marker icon and just replace the link to the one with the color of your choice. (i.e. marker-icon-2x-green.png
to some other image)
var greenIcon = new L.Icon({
iconUrl: 'https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-green.png',
shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41]
});
L.marker([51.5, -0.09], {icon: greenIcon}).addTo(map);