0
votes

i was use leaflet.js to draw about 10000 icon markers,because it is icon marker,so i cannot use circleMarker. I find a leaflet plugin Leaflet.Canvas-Markers,it can help me draw 10000 icon markers fast, but this plugin caused the click event to fail. This is my code

var ciLayer = L.canvasIconLayer({}).addTo(leafletMap)
    var icon = L.icon({
    iconUrl: 'StructWell.png',
    iconSize: [20, 18],
    iconAnchor: [10, 9]
    });
    function markerClickHandler (e) {
        console.log(e)
        console.log()
    }
    let markers = []
    SiteList.results.forEach((site, i) => {
        var marker = L.marker([site.latitude, site.longitude], {icon: icon, title: JSON.stringify(site)})
        marker.on('click', markerClickHandler)
        // ciLayer.addMarker(marker)
        markers.push(marker);
    })
    ciLayer.addLayers(markers);

function markerClickHandler do not work when i click the marker. was I do some bug,or are there any more solutions. The key is large number of icon markers with click event. thanks

1
why you call ciLayer.addMarker(marker) and then ciLayer.addLayers(markers);?Falke Design
sorry I do a mistake,code ciLayer.addMarker(marker) is a test, but I remove this code, click event also not workfreddie.wang

1 Answers

0
votes

Listener should be added like below:

 ciLayer.addOnClickListener(function (e,data) {
      console.log(data)
 });

var map = L.map('map').setView([59.9578,30.2987], 10);
    var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
      preferCanvas: true
    }).addTo(map);

    var ciLayer = L.canvasIconLayer({}).addTo(map);

    ciLayer.addOnClickListener(function (e,data) {
    console.log(data[0].data.mydata)
    });
    

    var icon = L.icon({
      iconUrl: 'https://img.icons8.com/metro/26/000000/marker.png',
      iconSize: [20, 18],
      iconAnchor: [10, 9]
    });

  var markers = [];
    for (var i = 0; i < 10000; i++) {
      var marker = L.marker([58.5578 + Math.random()*1.8, 29.0087 + Math.random()*3.6], {icon: icon}).bindPopup("I Am "+i);
      marker.mydata="I Am "+i
    markers.push(marker);
    }
  ciLayer.addLayers(markers);
.map{
      width: 100%;
      height: 100px;
    }
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
  <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
  <script src="https://unpkg.com/[email protected]"></script>
  
  <div class="map" id="map"></div>

You can check examples provided by Leaflet.Canvas-Markers.

Hope this will helps you.