Search code examples
leafletreact-leafletreact-leaflet-v3

react leaflet have a broken marker


I have imported Leaflet module along with some code to delete the Icon.

import L from "leaflet";
import { Map, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";

delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
  iconRetinaUrl: require("./images/marker-icon-2x.png"),
  iconUrl: require("./images/marker-icon.png"),
  shadowUrl: require("./images/marker-shadow.png"),
});

The Marker Icons reside in my image folder. I also tried requiring directly:

L.Icon.Default.mergeOptions({
  iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"),
  iconUrl: require("leaflet/dist/images/marker-icon.png"),
  shadowUrl: require("leaflet/dist/images/marker-shadow.png"),
});

But still I get a broken marker.


Solution

  • If you're using create-react-app, this should work with the Webpack configuration. You must put this code somewhere where it will execute before your <Marker> elements render like at the top of your App.tsx file:

    import L from 'leaflet';
    import markerIcon2x from 'leaflet/dist/images/marker-icon-2x.png';
    import markerIcon from 'leaflet/dist/images/marker-icon.png';
    import markerShadow from 'leaflet/dist/images/marker-shadow.png';
    
    delete L.Icon.Default.prototype._getIconUrl;
    L.Icon.Default.mergeOptions({
        iconUrl: markerIcon,
        iconRetinaUrl: markerIcon2x,
        shadowUrl: markerShadow,
    })