agaidus / leaflet_webmaps_python

14 stars 14 forks source link

Why not use pandas through the folium workflow too? #1

Open dmvianna opened 6 years ago

dmvianna commented 6 years ago

Thanks for your tutorial, I'm finding it extremely useful.

However, the huge monolythic functions bother me. What's the point of doing one big hard to understand function and not just using global variables? It would be easier to read and refactor. Anyway, there's a third alternative: using pandas and composable small functions.

I favour a more functional style, and pandas really helps it.

def html(r):
    """
    Create some neat HTML for popup.
    Argument: pd.Series (row, use df.apply(html, axis=1))
    Returns: html string
    """
    return """
    <b>{0}</b><br>
    {1}<br>
    {2} {3}
    """\
        .format(r.Descript
                ,r.Address
                ,r.DateStr
                ,r.Time)

def marker(r):
    """
    Creates marker for folium use.
    Argument: pd.Series (row, use df.apply(marker, axis=1)
    Returns: folium.Marker object
    """
    popup_html = html(r)
    iframe = folium.IFrame(html=popup_html, width=300, height=100)
    popup = folium.Popup(iframe, max_width=2650)
    if r.Descript == 'BATTERY':
        icon = folium.Icon(color='red', icon='plus')
    else:
        icon = folium.Icon(color='blue', icon='star')
    return folium.Marker((r.geometry.y, r.geometry.x)
           ,icon=icon
          ,popup=popup)

assaults['marker'] = assaults.apply(marker, axis=1)

# Create effects in the world

crime_map = folium.Map([37.7556, -122.4399], zoom_start = 12)
assaults.marker.apply(lambda x: x.add_to(crime_map))

print(crime_map)

If I succeed with changing the rest of the code with this, I might write a pull request. Maybe as a branch, so you get to keep both styles?

dmvianna commented 6 years ago

MarkerClusters...

m = folium.Map([37.7556, -122.4399], zoom_start = 12)

cluster = folium.MarkerCluster(name='assaults')
assaults.marker.apply(lambda x: cluster.add_child(x))
m.add_child(cluster)
folium.LayerControl().add_to(m)
print(m)
agaidus commented 6 years ago

@dmvianna glad you found it useful. This is great! I definitely agree with your approach and the smaller functions using pandas. It certainly makes it more readable and flexible. Definitely let me know if you change the rest of the code in this style.