Search code examples
javascriptleafletmarker

How to pass dynamic data to the multiple markers in leaflet?


I want to pass some dynamic data to the markers which I am creating in a loop.

Finally when I click on any marker it is displaying last added marker data only.

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++;
  }

I want each and every marker should have their own data(i,e lattitude).


Solution

  • Can you try this code?

    <!DOCTYPE html>
    <html lang="en">
      <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>