Leaflet changing Marker color

Chromos picture Chromos · May 9, 2014 · Viewed 124.9k times · Source

Is there a way to randomly change marker-colors in native Leaflet? I'm using svg elements which could be styled. I know that it is possible with mapbox.js

EDIT: To clarify what I intend to do: If you add markers to the map via a doubleclick or something it should have random colors. To achieve this I wanted to use svg icons for the markers to style them.

This is my code:

myIcon = L.icon({
  iconUrl: "icon_33997.svg",
  iconAnchor: pinAnchor
});

newMarker = L.marker(lat, long], {
  icon: myIcon
});

Answer

tutts picture tutts · Nov 29, 2016

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.

Map with multiple coloured Markers