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

我想将一些动态数据传递给我在循环中创建的标记。


最后,当我点击任何标记时,它只显示最后添加的标记数据。


var i=0

//creating multilple markers

while(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++;

  }

我希望每个标记都应该有自己的数据(即纬度)。


鸿蒙传说
浏览 148回答 1
1回答

红颜莎娜

你能试试这个代码吗?<!DOCTYPE html><html>&nbsp; <head>&nbsp; &nbsp; <meta charset="UTF-8" />&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0" />&nbsp; &nbsp; <meta http-equiv="X-UA-Compatible" content="ie=edge" />&nbsp; &nbsp; <title>Document</title>&nbsp; &nbsp; <link&nbsp; &nbsp; &nbsp; rel="stylesheet"&nbsp; &nbsp; &nbsp; href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css"&nbsp; &nbsp; />&nbsp; &nbsp; <script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"></script>&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; * {&nbsp; &nbsp; &nbsp; &nbsp; margin: 0;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; #map {&nbsp; &nbsp; &nbsp; &nbsp; width: 100vw;&nbsp; &nbsp; &nbsp; &nbsp; height: 100vh;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </style>&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; <div id="map"></div>&nbsp; </body>&nbsp; <script>&nbsp; &nbsp; const coordinates = {&nbsp; &nbsp; &nbsp; Latitude: {&nbsp; &nbsp; &nbsp; &nbsp; '0': 17.7222014,&nbsp; &nbsp; &nbsp; &nbsp; '1': 17.3924217,&nbsp; &nbsp; &nbsp; &nbsp; '2': 17.3906471,&nbsp; &nbsp; &nbsp; &nbsp; '3': 17.433709,&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; Longitude: {&nbsp; &nbsp; &nbsp; &nbsp; '0': 83.2892612,&nbsp; &nbsp; &nbsp; &nbsp; '1': 78.4689988,&nbsp; &nbsp; &nbsp; &nbsp; '2': 78.5009093,&nbsp; &nbsp; &nbsp; &nbsp; '3': 78.5016144,&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; };&nbsp; &nbsp; const map = L.map('map').setView([17.3924217, 78.4689988], 7);&nbsp; &nbsp; L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {&nbsp; &nbsp; &nbsp; attribution:&nbsp; &nbsp; &nbsp; &nbsp; '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',&nbsp; &nbsp; }).addTo(map);&nbsp; &nbsp; for (let i = 0; i < Object.keys(coordinates.Latitude).length; i += 1) {&nbsp; &nbsp; &nbsp; const marker = L.marker([&nbsp; &nbsp; &nbsp; &nbsp; coordinates.Latitude[i.toString()],&nbsp; &nbsp; &nbsp; &nbsp; coordinates.Longitude[i.toString()],&nbsp; &nbsp; &nbsp; ]);&nbsp; &nbsp; &nbsp; marker.myData = { id: coordinates.Latitude[i.toString()] };&nbsp; &nbsp; &nbsp; marker.on('click', function(e) {&nbsp; &nbsp; &nbsp; &nbsp; alert(marker.myData.id);&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; marker.addTo(map);&nbsp; &nbsp; }&nbsp; </script></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript