Code With Wolf


How to Change Marker Color with React-Leaflet

How to Change Marker Color with React-Leaflet

I wanted to change the color of the default markers on a leaflet map in a react app. I was using react-leaflet npm package and was struggling to find how to do this in the documentation.

First and foremost, don't waste your time trying to do this with CSS. You are going to have a bad time.

Those markers are images, and trying to pinpoint how they will be overlayed over your map layer and within the map container and applying a dynamic id to them to style them is not worth it.

Here is how I did it:

import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import * as L from "leaflet";
import { useState } from "react";

export default function App() {

    //  Create the Icon
  const LeafIcon = L.Icon.extend({
    options: {}
  });

  const blueIcon = new LeafIcon({
      iconUrl:
        "https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|abcdef&chf=a,s,ee00FFFF"
    }),
    greenIcon = new LeafIcon({
      iconUrl:
        "https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|2ecc71&chf=a,s,ee00FFFF"
    });

    //  Use the state hook:
  const [icon, setIcon] = useState(blueIcon);

    // This function will change the state's icon:

  const changeIconColor = (icon) => {
    if (icon.options.iconUrl === greenIcon.options.iconUrl) {
      setIcon((current) => (current = blueIcon));
    } else {
      setIcon((current) => (current = greenIcon));
    }
  };
  return (
    <div className="App">
      <h1>React-Leaflet Map</h1>
      <h2>How to change a marker color</h2>

      <MapContainer
        style={{ height: "200px" }}
        center={[40.7608, -111.891]}
        zoom={13}
        scrollWheelZoom={false}
      >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        <Marker position={[40.7608, -111.891]} icon={icon}>
          <Popup>
            <h1>Salt lake City</h1>
            <button onClick={() => changeIconColor(icon)}>
              Change Marker Color
            </button>
          </Popup>
        </Marker>
      </MapContainer>
    </div>
  );
}

If you have the leaflet and react-leaflet npm modules installed, this should work for you. Click on the marker and you will see the popup with a "Change Marker Color" button. That should do the trick.

The idea here is that we are changing the Marker's image (it actually uses Google Map's pins here) and NOT trying to style Leaflet's default marker image. Trying to style that bad boy is going to give you a bad time.



© 2022 Code With Wolf