python-visualization / branca

This library is a spinoff from folium, that would host the non-map-specific features.
https://python-visualization.github.io/branca/
MIT License
111 stars 63 forks source link

Is there a way to remove a child from a parent element? #107

Closed alessioarena closed 1 year ago

alessioarena commented 2 years ago

In the past to remove an Element or MacroElement from its parent I used del parent._children[childName], but that seems a buggy operation. In several cases when rendering the parent the child is still there.

Is there a preferred way to remove a child from a parent element?

An example of the issue I'm having: Adding a Draw element to a Leaflet map using Folium image

Parent has the draw_control child image

JavaScript code injected to the resulting HTML element image

Now I removed the child from the _children attribute using the method above: image

The Draw element is still there when rendering! image

and the JavaScript code is still there

RohanG0407 commented 2 years ago

@alessioarena Any solution to this issue yet? I'm trying to delete a Marker frop the map by deleting its child in._children. It seems that the child get deleted from ._children but the Marker is still on the Map.

alessioarena commented 2 years ago

Unfortunately not at the moment. I think is something to do with the rendering of the leaflet map already done once with the child, and probably cached somewhere. However I could not find a solution apart from copying the children and attribute of the map to another brand new Map object. I can send you the snippet of code that worked for me if that is helpful

alessioarena commented 2 years ago

This is what I'm currently doing to copy a Map object:

def copy_map(map_obj):
    new_map = folium.Map()
    new_map.options = map_obj.options
    for k, v in map_obj._children.items():
        new_map.add_child(v)
    return new_map

You can then remove the child before is rendered, or just not add it in the first place by modifying this function and capturing a condition (child name, index and so on).

I'm not sure if that is generalized enough, there may be other attributes that you would like to copy to the new object, but for my case it worked

Conengmo commented 1 year ago

When we render, objects are added to the header, html and script attributes of the Figure object. To delete something, it has to be deleted there as well.

The way things are set up pretty much assumes a user renders once and that's it.

Thanks for sharing your workaround @alessioarena. I'll close the issue for now. If somebody wants to think about a cleaner, native way of deleting items, that's welcome.