redshift
redshift

Reputation: 5227

How to assign different colors to multiple markercluster groups?

I am working with the leaflet.markercluster plugin and have it working so it clusters my markers. Is it possible to assign a specific color to multiple cluster groups? Right now, all the cluster marker colors are the same between various layer groups and it's hard to differientate which layers represent which.

I want to use the default markerCluster marker styles, but I want to assign a different background-color to each group.

Example:

Group 1

var trucksGroup = L.markerClusterGroup({
    iconCreateFunction: function(cluster) {
        return L.divIcon({ /* assign color here?? */ });
    }
});

var carsGroup = L.markerClusterGroup({
    iconCreateFunction: function(cluster) {
        return L.divIcon({ /* assign color here?? */ });
    }
});

The default marker CSS:

.marker-cluster-small {
background-color: rgba(181, 226, 140, 0.6);
}
.marker-cluster-small div {
background-color: rgba(110, 204, 57, 0.6);
}

.marker-cluster-medium {
background-color: rgba(241, 211, 87, 0.6);
}
.marker-cluster-medium div {
background-color: rgba(240, 194, 12, 0.6);
}

.marker-cluster-large {
background-color: rgba(253, 156, 115, 0.6);
}
.marker-cluster-large div {
background-color: rgba(241, 128, 23, 0.6);
}`

Upvotes: 4

Views: 3007

Answers (1)

jchamberlain
jchamberlain

Reputation: 1068

I haven't tried it this, but here's what I recommend attempting:

  1. Instead of returning L.divIcon() from your function, get the default icon by calling _defaultIconCreateFunction() on your markerClusterGroup, e.g., trucksGroup._defaultIconCreateFunction(cluster).
  2. Add a new class to that default icon to denote what group it's in. E.g., icon.options.className += ' trucks-group'.
  3. Add new styles in your CSS for .truck-group.marker-cluster-small, .truck-group.marker-cluster-medium, etc.

Putting the first two steps together:

var trucksGroup = L.markerClusterGroup({
    iconCreateFunction: function(cluster) {
        var icon = trucksGroup._defaultIconCreateFunction(cluster);
        icon.options.className += ' trucks-group';
        return icon;
    }
});

var carsGroup = L.markerClusterGroup({
    iconCreateFunction: function(cluster) {
        var icon = carsGroup._defaultIconCreateFunction(cluster);
        icon.options.className += ' cars-group';
        return icon;
    }
});

Upvotes: 5

Related Questions