使用JavaScript打开/关闭传单标记弹出窗口

时间:2019-07-27 02:49:56

标签: leaflet

我有以下代码可创建一个新标记,每次单击时都会显示Drag me!

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

我可以使用JavaScript打开弹出窗口吗?我该怎么做?最初,我希望在创建时自动将其打开,但是我发现自己也需要在其他情况下将其打开。

1 个答案:

答案 0 :(得分:2)

使用本机传单的openPopup()方法。 Source

创建标记时,您要做的就是像这样调用此方法:

pin.openPopup();

每次要以编程方式打开标记时都要执行此操作。

<!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/leaflet@1.5.1/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin="" />
    <script src="https://unpkg.com/leaflet@1.5.1/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>