Search code examples
angulartypescriptleafletmarkers

How to show Leaflet markers in Angular?


I am using leaflet and after a lot of research i still cannot get my marker to show on my map.

I tried all the solutions I could find out there. Even the the angular workaround suggested by Leaflet. For now I managed to get the marker img, with the right path to render into the html, tho it still doesn't show the image. In other words, I get the right path, it finds the image, I can see all that in the console, but then says cannot load image, which is rather misleading because there is definitely nothing wrong with the image

below is my code:

let markerIcon = L.icon({ iconUrl: 'src/assests/icons/marker.png'});
L.marker([48.208, 16.373], {
      icon: markerIcon,
      riseOnHover: true
}).addTo(map);

below is the console of the rendered html in the browser with the correct path and everything:

<img src="src/assests/icons/marker.png" class="leaflet-marker-icon leaflet-zoom-animated leaflet-interactive" alt="" tabindex="0" style="transform: translate3d(659px, 207px, 0px); z-index: 207;">

I just wanted that marker to show up! Without markers my whole project is useless.


Solution

  • You need to pass an icon object which will define the path for the marker image like this:

    icon = {
        icon: L.icon({
          iconSize: [ 25, 41 ],
          iconAnchor: [ 13, 0 ],
          // specify the path here
          iconUrl: './node_modules/leaflet/dist/images/marker-icon.png',
          shadowUrl: './node_modules/leaflet/dist/images/marker-shadow.png'
       })
    };
    

    and then const marker = L.marker([51.5, -0.09], this.icon).addTo(map);

    No need to include the marker's image on the assets folder because it is already included in the Leaflet package.

    Here is a working demo with a marker and a popup using latest angular version.