Search code examples
pythonfolium

Folium - icon color based on current date - eval()?


I'm trying to set my map up so that the marker icons change color based on current date vs target date.

I'm able to achieve this by updating the generated HTML using regex:

var icon_4089458f0c8541b482236fb9d52bb7f9 = L.AwesomeMarkers.icon(
    {"date": "2021-10-21",
    "extraClasses": "fa-rotate-0",
    "icon": "info-sign",
    "iconColor": "white",
    "markerColor": eval('if (new Date("2021-09-01").setHours(0, 0, 0, 0) < new Date().setHours(0, 0, 0, 0)) { "lightgray" }
                         else if (new Date("2021-09-01").setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0)) { "red" }
                         else { "green" }'),
    "prefix": "glyphicon"}
);

However that is very clunky.

I tried passing the eval into folium.Icon(color= but that just creates an escaped string of the command and ends up not working.

Is there a way to pass something like this using folium so that it generates the map with the required eval?


Solution

  • Not sure if best solution, but went all the way to folium's Icon class and did a bit of hack and slash.

    color_js = r'''eval('if (new Date("''' + date_en + '''").setHours(0, 0, 0, 0) < new Date().setHours(0, 0, 0, 0)) { "lightgray" } else if (new Date("''' + date_en + '''").setHours(0, 0, 0, 0) == new Date().setHours(0, 0, 0, 0)) { "red" } else { "''' + clr + '''" }')'''
    my_ico = folium.Icon(icon="info-sign")
    my_ico.options.pop("markerColor")
    optns = re.sub("'", '"', re.sub("(?:\{|\})", "", str(my_ico.options)))
    template = u"""
            {% macro script(this, kwargs) %}
                var {{ this.get_name() }} = L.AwesomeMarkers.icon(
                    {""" + optns + u""", "markerColor": """ + color_js + u""" },
                );
                {{ this._parent.get_name() }}.setIcon({{ this.get_name() }});
            {% endmacro %}
            """
    my_ico._template = Template(template)
    folium.Marker([lat, lon], icon=my_ico).add_to(fmap)