1

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.

ghybs
  • 47,565
  • 6
  • 74
  • 99
Sai Krishnadas
  • 2,863
  • 9
  • 36
  • 69
  • 1
    What is your build process? Are you using create-react-app? webpack? Does it work with an external url like: `https://unpkg.com/leaflet@1.7.1/dist/images/marker-icon-2x.png`? If it does then your build process may not be bundling the required resources. If it does not work with an externally hosted image your code is likely the cause. – teddybeard Oct 05 '21 at 19:41

2 Answers2

2

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,
})
teddybeard
  • 1,964
  • 1
  • 12
  • 14
0

With leaflet-defaulticon-compatibility plugin, it should work without further code, provided that your build engine configuration is already setup to handle URL's in CSS:

$ npm install leaflet-defaulticon-compatibility --save

import 'leaflet/dist/leaflet.css';
import 'leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css'; // Re-uses images from ~leaflet package
import * as L from 'leaflet';
import 'leaflet-defaulticon-compatibility';

Disclaimer: I am the author of that plugin

ghybs
  • 47,565
  • 6
  • 74
  • 99