marker icon isn't showing in Leaflet

后端 未结 4 1493
栀梦
栀梦 2021-01-26 20:46

I \'ve put together a very simple React / Leaflet demo but the marker icon is not showing at all. Full running code is here.

Here\'s what I have in my componentDid

相关标签:
4条回答
  • 2021-01-26 21:05

    Just for reference, this is due to webpack trying to include the Marker Icon image file specified in Leaflet CSS as a static asset in different folder and possibly file renaming (e.g. for finger printing); all this interferes with Leaflet algorithm which uses that image only as a pointer to its actual CSS images folder, which therefore can be completely missing after webpack build step.

    See details in https://github.com/Leaflet/Leaflet/issues/4968

    I specifically made a Leaflet plugin to cover this issue: https://github.com/ghybs/leaflet-defaulticon-compatibility

    Retrieve all Leaflet Default Icon options from CSS, in particular all icon images URL's, to improve compatibility with bundlers and frameworks that modify URL's in CSS.

    Unfortunately, it would still not work in CodeSandbox (or even in StackBlitz), because the latter does not handle these static assets. It is visible by just trying to use Leaflet Layers Control, which uses a very simple CSS background image, which is also missing in CodeSandbox.

    But everything should be fine in your own environment.

    demo in CodeSandbox: https://codesandbox.io/s/elegant-swirles-yzsql

    and in StackBlitz (same static assets issue): https://stackblitz.com/edit/react-vqgtxd?file=index.js

    0 讨论(0)
  • 2021-01-26 21:20

    Here's what worked for me in the end (I'm on webpack):

    const defaultIcon = new L.icon({
      iconUrl: require('../node_modules/leaflet/dist/images/marker-icon.png'); // your path may vary ...
      iconSize: [8, 8],
      iconAnchor: [2, 2],
      popupAnchor: [0, -2]
    });
    
    generateMarkers().forEach( c=> {
       L.marker(c, {icon: defaultIcon}).addTo(this.map).bindPopup('a marker; yeah').openPopup();
    }
    
    0 讨论(0)
  • 2021-01-26 21:24

    Try to add an icon:

    const myIcon = L.icon({
       iconUrl: 'myIcon.png',
       // ...
    });
    
    L.marker([37.98, 23.72], {icon: myIcon})
      .addTo(this.map)
    

    Perhaps you have some problems with the default one: https://leafletjs.com/reference-1.6.0.html#icon-default

    0 讨论(0)
  • 2021-01-26 21:25

    I'm using react-leaflet. Here's how I did it.

    import markerIconPng from "leaflet/dist/images/marker-icon.png"
    import {Icon} from 'leaflet'
    

    then, later, inside the MapContainer:

    <Marker position={[lat, lng]} icon={new Icon({iconUrl: markerIconPng})} />
    
    0 讨论(0)
提交回复
热议问题