为了账号安全,请及时绑定邮箱和手机立即绑定

如何将动态数据传递给传单中的多个标记?

如何将动态数据传递给传单中的多个标记?

鸿蒙传说 2021-12-23 15:11:23
我想将一些动态数据传递给我在循环中创建的标记。最后,当我点击任何标记时,它只显示最后添加的标记数据。var i=0//creating multilple markerswhile(coordinates.Latitude[i]){           marker = new L.Marker(new L.LatLng(coordinates.Latitude[i],                            coordinates.Longitude[i]),{icon: greenIcon});           //adding data to the marker           marker.myData = { id: coordinates.Latitude[i] };           marker.on('click', function (e) {                    alert(marker.myData.id);           });           map.addLayer(marker);           i++;  }我希望每个标记都应该有自己的数据(即纬度)。
查看完整描述

1 回答

?
红颜莎娜

TA贡献1842条经验 获得超13个赞

你能试试这个代码吗?


<!DOCTYPE html>

<html>

  <head>

    <meta charset="UTF-8" />

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

    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <title>Document</title>

    <link

      rel="stylesheet"

      href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"

    />

    <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"></script>

    <style>

      * {

        margin: 0;

      }


      #map {

        width: 100vw;

        height: 100vh;

      }

    </style>

  </head>

  <body>

    <div id="map"></div>

  </body>

  <script>

    const coordinates = {

      Latitude: {

        '0': 17.7222014,

        '1': 17.3924217,

        '2': 17.3906471,

        '3': 17.433709,

      },

      Longitude: {

        '0': 83.2892612,

        '1': 78.4689988,

        '2': 78.5009093,

        '3': 78.5016144,

      },

    };


    const map = L.map('map').setView([17.3924217, 78.4689988], 7);


    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);


    for (let i = 0; i < Object.keys(coordinates.Latitude).length; i += 1) {

      const marker = L.marker([

        coordinates.Latitude[i.toString()],

        coordinates.Longitude[i.toString()],

      ]);

      marker.myData = { id: coordinates.Latitude[i.toString()] };


      marker.on('click', function(e) {

        alert(marker.myData.id);

      });


      marker.addTo(map);

    }

  </script>

</html>


查看完整回答
反对 回复 2021-12-23
  • 1 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号