Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet + MarkerCluster + custom Icons + Popups

I'd like to use custom icons for my markers, while using Leaflet MarkerCluster.

I already managed to implement my custom icons, but now the marker popups aren't working any more.

My code looks like this:

var markers1 = new L.MarkerClusterGroup();

// add markers with popup info
var geoJsonLayer1 = L.geoJson(Myplaces, {
   onEachFeature: function(feature, layer) {
      layer.bindPopup(feature.properties.Name);
   }
})

// add markers with custom icons
var geoJsonLayer1 = L.geoJson(Myplaces, {
   onEachFeature: onEachFeature,
   pointToLayer: function(feature, latlng) {
      var iconURL = feature.properties.img;
      return new L.Marker(new L.LatLng(feature.geometry.coordinates[1], feature.geometry.coordinates[0]), {
         icon: L.icon({
            iconAnchor: [0, 0],
            popupAnchor: [0, 0],
            iconUrl: iconURL
         })
      });
   }
})

// add markers to map
markers1.addLayer(geoJsonLayer1);
map.addLayer(markers1);

When I remove the part for the custom icons (the section below "// add markers with custom icons"), the marker popups work just fine again…

Any suggestions? Thanks so much in advance for any help!!

(I tried everything I could think of & I'm going crazy here…) ; )

like image 598
julia Avatar asked Mar 10 '14 18:03

julia


1 Answers

Edit: Oops! misunderstood your question. Yeah the issue is you are doing L.geoJson twice and doing different things with them. This function returns a new L.GeoJson object, so the things you add your popups to are not the things you are making custom markers. So yeah you should just combine them.

var geoJson = L.geoJson(geoJsonData, {
    pointToLayer: function(obj) {
        var mark = L.circleMarker(obj.geometry.coordinates, obj.properties);
        mark.bindPopup('<div>' + marks.length + '</div>');
        return mark;
    }
});

This piece of code is from and updated example I did here.

I'll leave in the bit below about custom cluster icons.

As a side note, it's typically bad practice to attempt to create two vars with the same name, and most linters will complain about that.

...

I created a little demo that uses clustering, popups and custom icons here.

When you create the MarkerClusterGroup you can give it an arbitrary function with creates the icons for clusters:

iconCreateFunction: function(cluster) {
    var count = cluster.getChildCount();
    return L.divIcon({
        html: '<span class="custom">' + (count + 100) + '</span>'
    })
}

Where you can put your logic for custom cluster icons. For single markers, you can pass an icon the the constructor directly. You'll also notice that popups work for markers and clusters.

EDIT: The previous jsfiddles now have incompatibility with leaflet and markercluster versions. Here is a working version

Hope this helps!

like image 199
hassassin Avatar answered Oct 23 '22 07:10

hassassin