0
votes

I'm using react-leaflet and want a custom marker icon. React-leaflet can take a Leaflet.Icon object to display a custom marker icon. So I NPM installed leaflet, and added import { L } from 'leaflet';.

I then added:

const FPIcon = L.Icon.extend({
  options: {
    iconSize: [38, 95],
    iconAnchor: [22, 94],
    popupAnchor: [-3, -76]
  }
});

const purpleIcon = new FPIcon({
          iconUrl: '%PUBLIC_URL%/markers/Bar-Marker.png'
        });

to my render method.

But I keep getting the following error Cannot read property 'Icon' of undefined.

To achieve a custom marker icon, I've also tried the following:

const purpleIcon = L.icon({
    iconUrl: '%PUBLIC_URL%/markers/Bar-Marker.png',
    iconSize: [38, 95],
    iconAnchor: [22, 94],
    popupAnchor: [-3, -76]
});

but again got a Cannot read property 'icon' of undefined error.

Any ideas on what I'm doing wrong?

2
In the second example the bracket are not closed correctly, remove } at the end. And what happend if you use an url like unpkg.com/[email protected]/dist/images/marker-icon.png ? - Baptiste
Good spot, although I didn't have that rogue bracket there when I tried it, I've just tried with the url above and it makes no difference :( - JL9
And if you console.log(purpleIcon) ? - Baptiste
Undefined, it's crashing on const FPIcon = L.Icon.extend({ - JL9
Can you post all of the code from the file? I can't be sure, but my guess is that you're not importing leaflet, so the L variable is undefined. - Evan Siroky

2 Answers

0
votes

Your leaflet import is wrong. Import leaflet as follows after that it will work as expected:

import L from 'leaflet';