Search code examples
pythonfolium

Assertion error in Folium - "cannot render this Element if it's not in a Figure"


Trying to use Folium to generate an interactive map from locations in a pandas dataframe. However, when I try to save the map as an HTML file, I get an Assertion Error: "You cannot render this Element if it's not in a Figure".

The only relevant information I've been able to find is an older forum post that was closed without enough detail for me to see how to fix it:

https://github.com/python-visualization/folium/issues/495

My code:

data = pd.read_csv(in_file)

route_map = folium.Map(location=[data['"PosLat"'].mean(), data['"PosLon"'].mean()],
                       zoom_start=10, tiles='OpenStreetMap')

for lat, lon, date in zip(data['"PosLat"'], data['"PosLon"'], data['"Date"_"Time"']):
    folium.Marker(location=[lat, lon],
                  icon=folium.Icon(color='blue').add_to(route_map))

out_file = input('Enter file name: ')
if '.html' not in out_file:
    out_file += '.html'

route_map.save(out_file)

Error:

Traceback (most recent call last):
  File "interactive_map_gen.py", line 21, in <module>
    route_map.save(out_file)
  File "C:\Program Files\Python36\lib\site-packages\branca\element.py", line 157, in save
    html = root.render(**kwargs)
  File "C:\Program Files\Python36\lib\site-packages\branca\element.py", line 301, in render
    child.render(**kwargs)
  File "C:\Program Files\Python36\lib\site-packages\folium\map.py", line 299, in render
    super(LegacyMap, self).render(**kwargs)
  File "C:\Program Files\Python36\lib\site-packages\branca\element.py", line 617, in render
    element.render(**kwargs)
  File "C:\Program Files\Python36\lib\site-packages\branca\element.py", line 598, in render
    assert isinstance(figure, Figure), ("You cannot render this Element "
AssertionError: You cannot render this Element if it's not in a Figure.

The only suggested workaround in the above forum thread was to import the colormap from folium instead of branca, but I haven't been able to find anything on how to do that. I've tried re-installing folium, I've tried setting the output file name to a fixed string. I'm at a loss. Everything follows the examples for folium 0.3.0 at https://pypi.python.org/pypi/folium. Is there something I'm missing?


Solution

  • I figured it out - simple syntax error that I missed repeatedly.

    In the loop where I'm adding the markers, the proper syntax is

    folium.Marker(pos, icon).add_to(map)

    As I have it now, I'm trying to add the icon parameter to the map, not the whole marker.