Add layergroups to map and update by name

1.2k Views Asked by At

I'm currently using ngx-leaflet 4.0.0 with Angular 6.x and RXjs 6.x. I have a bunch of observable that generate/stream Layers which should be drawn on the map.

When we have a lot of markers then, as you might expect, the performance degrades. This probably has to do with the fact that I basically concat all the markers in to one single array which I pass to leafletLayers.

Ideally I only add, remove or update a single layergroup using its name. Unfortunately I don't know how to use LayerGroups as is suggested as one of the two performance enhancements when working with a large number of markers. I want to use a data structure as you see below, should this be possible?

blueLayerGroup: L.LayerGroup
redLayerGroup: L.LayerGroup

{
   "BlueShips": blueLayerGroup,
   "RedShips": redLayerGroup    
}

I'm not using the leafletMapControl, we have our own custom ui for selecting layers.

1

There are 1 best solutions below

0
On

If you want to try to use layerGroups, you could try to emulate the following approach:

In your component, just have two layer groups that you add to your leaflet layers array:

redLayerGroup = L.layerGroup();
blueLayerGroup = L.layerGroup();
layers = [ blueLayerGroup, redLayerGroup ];

Then, you just add layers to or remove layers from the layer groups as needed:

addLayerToLayerGroup(layer: L.Layer, layerGroup: L.LayerGroup) {
  layerGroup.addLayer(layer);
}

removeLayerFromLayerGroup(layer: L.Layer, layerGroup: L.LayerGroup) {
  layerGroup.removeLayer(layer);
}

This approach doesn't rely on ngx-leaflet to sync the markers. Ngx-leaflet is only handling the layerGroups themselves (if they are added or removed from the layers array).

This may or may not solve your performance issue, though. I always found more than a couple hundred markers made Leaflet slow down in general. If it works for you, there's a Leaflet.markercluster plugin for ngx-leaflet. It helps reduce the total number of markers actually rendered to the map at any time to help performance.