How to use require to import a custom icon with react leaflet?

4.1k Views Asked by At

I have read several posts here on stackoverflow like React Leaflet - How to render custom image using Circle Markers and custom marker icon with react-leaflet On how to include custom icons in react leaflet maps. I have tried the below code

const newicon = new L.icon({
      iconUrl: require('../assets/Download-Image.png'),
      iconSize: [30, 30]  
    })

but the image does not render on the map.

However, if I use the url of the same icon as below it works and renders. Any advise on what I could be doing wrong?

const newicon = new L.icon({
      iconUrl: 'https://www.somewebsite/Download-Image.png',
      iconSize: [30, 30]  
    })
1

There are 1 best solutions below

3
On

You should not place require between '': only the image path inside require.

const newicon = new L.icon({
  iconUrl: require("./assets/marker.png"),
  iconSize: [30, 30]
});

export default function App() {
  const position = [51.505, -0.09];

  return (
    <Map center={position} zoom={13} style={{ height: "500px" }}>
      <TileLayer
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      />
      <Marker position={position} icon={newicon}>
        <Popup>
          A pretty CSS3 popup.
          <br />
          Easily customizable.
        </Popup>
      </Marker>
    </Map>
  );
}

Another approach, which is mostly used would be to import the image like below:

import marker from "./assets/marker.png";

and then use it like this:

const newicon = new L.icon({
  iconUrl: marker,
  iconSize: [30, 30]
});

Demo