Styling individual markers in markercluster

627 views Asked by At

I am trying to style individual markers, or clusters of size 1, based on some feature property.

var markers = L.markerClusterGroup();

function onEachFeature(feature, layer) {
  if (feature.properties.EncounterType && feature.properties.Year) {
    layer.bindPopup(feature.properties.EncounterType + " in " +
      feature.properties.Year);
  }
}

function style(feature) {
  switch (feature.properties.EncounterType) {
    case 'Shooting':
      return {
        color: "ff0000"
      };
    case 'Sighting':
      return {
        color: "0000ff"
      };
    case 'Hunting':
      return {
        color: "ff0000"
      };
  }
}

var geoJsonLayer = L.geoJSON(storer, {
  onEachFeature: onEachFeature
}, {
  style: style
});

markers.addLayer(geoJsonLayer);
map.addLayer(markers);

The onEachFeature function successfully creates the popups. However, the style function does not change the color of the clusters of size 1. I've tried using the iconCreateFunction when initializing the markerclustergroup, however, that did not work either.

1

There are 1 answers

5
ghybs On BEST ANSWER

Your style option is separated in a 3rd argument of your call to L.geoJSON factory, whereas it should have been placed within the 2nd argument, alongside onEachFeature option.

var geoJsonLayer = L.geoJSON(storer, {
  onEachFeature: onEachFeature,
  style: style
});

But that is probably not the only reason for your issue.

style option will apply to vector shapes (polylines, polygons, etc.), i.e. to non-point data. It may also apply to Circle Markers, which can be used for Point type geometries, but you have to explicitly create them (typically through the pointToLayer option).

Those non-point data cannot be handled by Leaflet.markercluster.

Therefore if you see "clusters of size 1" (I guess you mean markers), they come from unstyled Point type geometries in your storer GeoJSON data.

This is a normal marker:

Leaflet default marker

It is a PNG image that cannot be styled.

If you want to customize the appearance of your Point geometries, use custom icons, a plugin that provide such custom icons, or Circle Markers which you can modify the colour easily (including through the style option).

For example, if you were to choose that last option, you could do something like:

var geoJsonLayer = L.geoJSON(storer, {
  pointToLayer: function (geoJsonPoint, latlng) {
    return L.circleMarker(latlng);
  },
  onEachFeature: onEachFeature,
  style: style
});