javascriptcssleafletfont-awesome

How to use font awesome as an icon in leaflet instead of marker


In this code, I was using data[key].category to indicate related Icon as the marker. but I want to replace it with font-awesome icons to make it light-weight on runtime in some places may load over tens of icons as the markers

var Cofee= Leaflet.icon({
      iconUrl: '/img/Coffee.png',
      shadowUrl: '/img/pale-shadow.png',
      iconSize: [34, 49], 
      shadowSize: [49, 49],
      iconAnchor: [5, 62],
      shadowAnchor: [4, 62],
      popupAnchor: [12, -30]
});
var Store= Leaflet.icon({
      iconUrl: '/img/Store.png',
      shadowUrl: '/img/pale-shadow.png',
      iconSize: [34, 49], 
      shadowSize: [49, 49],
      iconAnchor: [5, 62],
      shadowAnchor: [4, 62],
      popupAnchor: [12, -30]
});
..
..
..

this.Getlatlng(currentlatlng, 9000).then(data => {
    for (var key in data) {
        Leaflet.marker(data[key].location, { icon: data[key].category })      
         .addTo(this.map).bindPopup('<h4>'+data[key].caption+'</h4>');
          markers.push([data[key].location.lat,data[key].location.lng]);
}

Solution

  • You can use font-awesome icons instead of built-in marker icons like this:

    const fontAwesomeIcon = L.divIcon({
        html: '<i class="fa fa-map-marker fa-4x"></i>',
        iconSize: [20, 20],
        className: 'myDivIcon'
    });
    
    L.marker([51.5, -0.09],{ icon:  fontAwesomeIcon}).addTo(map)
        .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
    

    const map = L.map('mapid').setView([51.505, -0.09], 8);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);
    
    const fontAwesomeIcon = L.divIcon({
      html: '<i class="fa fa-map-marker fa-4x"></i>',
      iconSize: [20, 20],
      className: 'myDivIcon'
    });
    
    L.marker([51.5, -0.09], {
        icon: fontAwesomeIcon
      }).addTo(map)
      .bindPopup('A pretty CSS3 popup.<br> Easily customizable.')
    #mapid {
      height: 100vh;
    }
    
    body {
      margin: 0px;
    }
    
    .leaflet-popup-close-button {
      display: none;
    }
    
    .myDivIcon {
      text-align: center;
      /* Horizontally center the text (icon) */
      line-height: 20px;
      /* Vertically center the text (icon) */
    }
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.4.0/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="" />
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    
    <script src="https://unpkg.com/leaflet@1.4.0/dist/leaflet.js" integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin=""></script>
    
    <div id="mapid"></div>