Search code examples
htmlcssangulartypescriptleaflet

Leaflet custom marker(divIcon) html/css does not apply


I'm currently attempting to customize the leaflet marker using a divIcon and custom html. The goal is to display my marker similar to this: vehicle tag

I am able to create a marker and a divIcon with the following code:

    leaflet.marker(NETHERLANDS_CENTER, {
      icon: leaflet.divIcon({
        html: '<div class="vehicle-container"><div><img src="../../assets/images/bus-solid.svg" width="16" height="16"/></div><div><p>HTM</p></div></div>',
      })
    }).addTo(this.map);

This results in the following being displayed on the map:
map result 1

This code is in my angular map component that has its own css file. However, no matter what I do in this css file it has no effect on the styling of what is displayed on the map.

I have tried customizing the vehicle-container class with any random things to just have an effect. I have tried using the className property of the divIconOptions which does remove the white square but further does not change anything by customizing the css for that class name.

I have also inspected the marker and saw that it was wrapped in an element of class .leaflet-div-icon which I attempted to change the styling of to no effect.

Is there any trick to making the styling of leaflet markers or how should I do it?


Solution

  • You can add inline styles in a kind-of readable way like this:

     //your styles go here
     const markerHtmlStyles = `
          background-color: #fff;
          width: fit-content;
          height: 3rem;`
    
    leaflet.marker(NETHERLANDS_CENTER, {
          icon: leaflet.divIcon({
            html: `<div style="${markerHtmlStyles}" class="vehicle-container"><div><img src="../../assets/images/bus-solid.svg" width="16" height="16"/></div><div><p>HTM</p></div></div>`,
          })
        }).addTo(this.map);
    
    

    And yeah, set the className to be '' in order to avoid the white square. Manipulate the CSS file for the markers accordingly so that you don't get the default styling.

    there probably is a better way but this is the quickest way to do it.