问题
I am currently working on a map visualization with the Leaflet library. I am also using the markercluster plugin to cluster my points.
So my question now is the following:
I have 3 different categories of Markers in 3 different layers. For example Restaurants, Cafes and Bars Layers. And I want to combine all active Layers to a specific cluster.
At the moment the entries are clustered separately but I want to cluster them together.
The next step would be coloring the cluster according to the childMarkers. E.g. cluster includes restaurant and bar markers => half red/ half green, only restaurants => only red etc.
I hope somebody can help me to get to a solution. Thank you!
回答1:
You mention 2 different requests in your question:
- Having 3 different types of markers, but all should cluster together. Tricky part is if you want to hide/show a specific type (maybe through Layers Control).
- Customizing the clusters appearance based on the number of contained markers from each type.
As for point 1, you can obviously add all 3 types of markers to the same MarkerClusterGroup, so that they can cluster together. If you already have them within different LayerGroups, you can simply do myMCG.addLayers([layerGroup1, layerGroup2, layerGroup3]);
and MCG will get all individual markers added. But refrain from adding/removing those LayerGroups to/from the map later!
The difficult part is when you want to be able nevertheless to dynamically add / remove a specific type of markers from the map. Instead of doing just map.removeLayer(layerGroupX);
, you would need to loop through all individual markers and remove them from your MCG, for example:
layerGroupX.eachLayer(function (marker) {
myMCG.removeLayer(marker);
});
See also this issue on MarkerClusterGroup plugin site for the reasons and some extra examples. Do the reverse for adding markers back into your MCG.
Edit: I have published a Leaflet.FeatureGroup.SubGroup plugin since then, which addresses this exact use case. See also Using several Marker Cluster Groups displays overlapping Clusters
As for point 2, simply refer to the Customising the Clustered Markers section of the plugin documentation. Basically, you use option iconCreateFunction
when initializing your MCG. You pass in a function, which takes a single argument (e.g. cluster
) and you can use cluster.getAllChildMarkers();
to get the array of contained markers in the cluster being styled. Then simply iterate through this array to count the number of each type of markers, and create an icon accordingly.
You could also try this other plugin: q-cluster. But it does not animate, so it is far less eye-candy than MCG…
来源:https://stackoverflow.com/questions/33143237/cluster-multiple-layers-with-markercluster