3

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]  
    })
kboul
  • 13,836
  • 5
  • 42
  • 53
dontke
  • 99
  • 3
  • 10

1 Answers1

3

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

kboul
  • 13,836
  • 5
  • 42
  • 53
  • Thanks @Kboul but `require` between the quotation marks was a typo on my post, I fixed it. Anyway I had tried your suggestions before, but still can't get the image to render in the map. I just get the no image available icon. Not sure if it's an issue with the package I have or not. – dontke Oct 26 '20 at 15:40
  • Did you try the 2nd approach? – kboul Oct 26 '20 at 16:25
  • I could help if you were able to provide a demo with your app. – kboul Oct 27 '20 at 09:14