Home > Net >  Why is my custom React-leaflet marker not displaying on my map?
Why is my custom React-leaflet marker not displaying on my map?

Time:11-15

I am trying to make a custom marker icon for my leaflet component in react. I am defining an icon class and attempting make the iconURL the location of the PNG I use. The issue that I am running into is that the iconURL is only working for 'https://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=•|abcdef&chf=a,s,ee00FFFF'.

I also tried using the directory of a PNG in my project, as well as a URL of an icon provided by google, for example 'https://fonts.google.com/icons?selected=Material Icons Outlined:cable:'. These both however do not display the image correctly. Is it an issue with the specific PNGs that I am using? I tried overriding the default URL icon with L.Icon.Default.prototype.options.iconUrl however it just produced the same results. Below will also be an image of what the icon looks like when attempting to use the icons that do not work currently.

(EDIT: Including an image of my directory in case it helps) enter image description here

icon not displaying correctly

 function OutageIndicator({ outage }) {
   const LeafIcon = L.Icon.extend({
      options: {
          iconSize:     [38, 95],
          shadowSize:   [50, 64],
          iconAnchor:   [22, 94],
          shadowAnchor: [4, 62],
          popupAnchor:  [-3, -76]
      }
    });

    L.Icon.Default.prototype.options.iconUrl = 'icons/marker.png';

    const streamingIcon = new LeafIcon({
      iconUrl:"icons/marker.png"
    });
    
  return !coords ? (
      "Loading"
    ) : (
      <Marker position={[coords.lat, coords.lng]} icon={streamingIcon}>
        <Popup className={outage.service_type}>
          {outage.service_type}: {outage.service_name}
        </Popup>
      </Marker>
    );
}

function OutageMap() {
//a bunch of other lines of code

  return (
    <>
      <button onClick={setReportIsOpenTrue}>Report Outage</button>
      <MapContainer center={[44, -85]} zoom={7} scrollWheelZoom={true}>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />

        {allOutages.map((mock) => (
          <OutageIndicator outage={mock} />
        ))}
      </MapContainer>
    </>
  );
}

export default OutageMap;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Since you are using React, there is probably a webpack build tool configured under the hood, with a file or url-loader.

In that case, you have to import or require your icon file, so that webpack knows that it must include it in your bundle:

    const streamingIcon = new LeafIcon({
      iconUrl: require("./icons/marker.png")
    });
  • Related