Search code examples
javascriptleafletpopupmarker

How to label markers similar to Google Maps in Leaflet


I am using Leaflet to load bing map tiles. The map is loading fine and I am able to put markers on the map.

But I want to know how to show label for the markers similar to the way they are shown in Google Maps i.e. a text attached to marker.

The way I want to show markers and its description on map:

I looked into the Leaflet documentation. I found Popup and Tooltip, but they don't provide the type of view I want.

Does anybody know of some functionality in Leaflet through which I can achieve the required behaviour.


Solution

  • To achieve that behavior you need to hide the popup content wrapper and use L.icon to place the popup content in your desired position by providing x, y coordinates

    var map = L.map('mapid').setView([51.505, -0.09], 5);
    
    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);
    
    var popup1 = L.popup({
      closeOnClick: false,
      autoClose: false
    }).setContent("A pretty CSS3 popup.");
    
    L.marker([52.5, -0.09]).addTo(map)
      .bindPopup(popup1)
      .openPopup();
    
    var yourIcon = L.icon({
      iconUrl: 'https://unpkg.com/leaflet@1.3.3/dist/images/marker-icon.png',
      popupAnchor: [30, 120]
    });
    
    var customOptions = {
      'className': 'custom',
    }
    
    var popup2 = L.popup({
      closeOnClick: false,
      autoClose: false
    }).setContent("A pretty CSS3 popup.<br> Easily customizable.'");
    
    
    L.marker([51.5, -0.09], {
        icon: yourIcon
      }).addTo(map)
      .bindPopup(popup2, customOptions).openPopup();
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"></script>
    
    <style>
      #mapid {
        height: 100vh;
      }
      
      .custom .leaflet-popup-close-button,
      .custom .leaflet-popup-tip-container {
        display: none;
      }
      
      .custom .leaflet-popup-content-wrapper,
      .custom .leaflet-popup-tip {
        background-color: transparent;
        -webkit-box-shadow: none;
        -moz-box-shadow: none;
        box-shadow: none;
      }
      
      .custom .leaflet-popup-content {
        font-size: 1.2rem;
        color: blue;
      }
    </style>
    <div id="mapid"></div>