GFL
GFL

Reputation: 1424

Open/Close Leaflet Marker Popup Using JavaScript

I have the following code which creates a new marker that says Drag me! every time it's clicked.

pin = L.marker([map.getCenter().lat, map.getCenter().lng], {icon:greenIcon, draggable:true, autoPan:true}).addTo(map);
pin.bindPopup('Drag me!');

Can I open the popup using JavaScript? How would I do that? Initially I'd like to have it automatically open when created, but I can see myself needed to open it for other situations too.

Upvotes: 0

Views: 552

Answers (1)

kboul
kboul

Reputation: 14570

Use native leaflet's openPopup() method. Source

When you create your marker all you have to do is to invoke this method like this:

pin.openPopup();

Do it everytime you want to open the marker programatically.

<!DOCTYPE html>
<html>

  <head>

    <title>Quick Start - Leaflet</title>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />

    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og==" crossorigin=""></script>



  </head>

  <body>



    <div id="mapid" style="width: 600px; height: 400px;"></div>
    <script>
      var map = L.map('mapid').setView([51.505, -0.09], 13);

      L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
          '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
          'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox.streets'
      }).addTo(map);
      
      var greenIcon = L.icon({
    iconUrl: 'https://leafletjs.com/examples/custom-icons/leaf-green.png',
    shadowUrl: 'https://leafletjs.com/examples/custom-icons/leaf-shadow.png',

    iconSize:     [38, 95], // size of the icon
    shadowSize:   [50, 64], // size of the shadow
    iconAnchor:   [22, 94], // point of the icon which will correspond to marker's location
    shadowAnchor: [4, 62],  // the same for the shadow
    popupAnchor:  [-3, -76] // point from which the popup should open relative to the iconAnchor
});

      const pin = L.marker([map.getCenter().lat, map.getCenter().lng], {
        icon: greenIcon,
        draggable: true,
        autoPan: true
      }).addTo(map);

      pin.bindPopup('Drag me!');
      pin.openPopup();

    </script>



  </body>

</html>

Upvotes: 3

Related Questions