I have a JS array of markers and would like to create layerGroup objects based on icon value.
arrayMarkers = [marker1, marker2, marker3, marker4, marker5, marker6];
arrayMarkers content by line (markers ordered by icon):
marker1 = L.marker ([4.8,44.7], {icon :’http://…icon_A.png’})
marker2 = L.marker ([4.1,44.2], {icon :’http://…icon_A.png’})
marker3 = L.marker ([4.5,44.9], {icon :’http://…icon_B.png’})
marker4 = L.marker ([4.2,44.5], {icon :’http://…icon_B.png’})
marker5 = L.marker ([4.2,44.5], {icon :’http://…icon_B.png’})
marker6 = L.marker ([4.9,44.7], {icon :’http://…icon_C.png’})
Goal : arrayLayerGroup = [layer1, layer2, layer3];
arrayLayerGroup content:
layer1 = L.layerGroup ([marker1, marker2])
layer2 = L.layerGroup ([marker3, marker4, marker5])
layer3 = L.layerGroup ([marker6])
I have tried this code, optionIcon brings back 'http://...icon_A.png' as expected, but have no clue how to compare values from same array. I can't compare line by line as coordinates are always different:
var j=1;
for (i=0; i<arrayMarkers.length; i++){
var optionIcone = arrayMarkers[i].options.icon.options.iconUrl;
var optionIcone2 = arrayMarkers[j].options.icon.options.iconUrl;
if (optionIcone !== optionIcone2){
var layer = L.layerGroup([arrayMarkers[i]]);
arrayLayerGroup.push(layer);
j++;
}
}
For example using Lodash groupBy:
// Group the Markers by iconUrl
var markersGroupedByIconUrl = _.groupBy(arrayMarkers, "options.icon.options.iconUrl");
// Convert each group of Markers which have same iconUrl into a Layer Group
var arrayLayerGroup = Object.values(markersGroupedByIconUrl)
.map((listOfMarkers) => L.layerGroup(listOfMarkers));