MazeMap / Leaflet.LayerGroup.Collision

Leaflet plugin for uncluttering L.Markers using basic collision detection.
MIT License
99 stars 36 forks source link

collision.removeLayer(marker); doesn't function as expected (SOLUTION) #18

Open CosmicDev-Official opened 2 months ago

CosmicDev-Official commented 2 months ago

This plugin has been a great solution to all of my point collision issues thus far (without using markerclusters or similar copycat plugins), however, recently I've been incorporating features into my map which include deleting specific points.

First, let me be clear: this is an issue, but one that I've solved and I'm documenting it here for anyone who is looking to use this plugin but may have this issue.

If you want to remove a marker from the collision layer, you'll need to do: collision.removeLayer(marker); Assuming you already have the marker object still. If you don't, I recommend creating a global dictionary or array and appending each point to it when it's created. If you use a dictionary, you can provide your own ID to it instead of looping through and searching each point as you would for an array if you're trying to find a specific point.

This plugin works by having an array of markers that are currently showing, and another array of all markers whether visible or not. When you zoom in, the code will use "rbush" to detect which points are colliding and which aren't, and will remove/add them to the layer. Because of how that works, the code needs to have another way to store information on every marker that isn't relying on the layer itself, because if it did rely on the layer when the points are removed they'd be forever forgotten. This is why it uses an array of all markers. Said array is very similar to what I referred to above in storing markers, but this is used by the plugin only and not by you.

The issue with this is that when you call .removeLayer() on the collision layer, the plugin doesn't define an override for the removeLayer function, and as such the marker is technically removed from the map/layer, but it isn't removed from the array of all the markers that the plugin uses, and as such when you zoom in or zoom out again the plugin will at some point re-create the deleted marker.

A fix for this isn't very hard, I ran it through ChatGPT and it worked first try. Here's the solution code that you can append to the end of the plugin JS file: `L.LayerGroup.Collision.prototype.removeLayer = function(layer) { // Remove from original layers this._originalLayers = this._originalLayers.filter(l => l !== layer);

// Remove from visible layers this._visibleLayers = this._visibleLayers.filter(l => l !== layer);

// Remove from the map L.LayerGroup.prototype.removeLayer.call(this, layer); };`

CosmicDev-Official commented 2 months ago

whoops