I am trying to plot folium polyLine with my dataframe. I have this kind of data
Datetime Lat lon Cars
2021-06-01 4.5 1.1 Car1
2021-06-01 4.8 0.8 Car1
2021-06-01 4.4 0.9 Car2
2021-06-02 4.7 1.0 Car2
I want to plot Folium.PolyLine but with temporal dimension like HeatMapwithtime.
Anyone can help me?
Thank in advance
Here is a simple example of how to do this:
import folium
import pandas as pd
from folium.plugins import TimestampedGeoJson
data = {
'Datetime': ['2021-06-01', '2021-06-01', '2021-06-01', '2021-06-02', '2021-06-02', '2021-06-02'],
'Lat': [4.5, 4.8, 4.4, 4.7, 4.6, 4.9],
'Lon': [1.1, 0.8, 0.9, 1.0, 1.2, 1.3],
'Cars': ['Car1', 'Car1', 'Car2', 'Car2', 'Car1', 'Car2']
}
df = pd.DataFrame(data)
grouped_data = {date: group[['Lat', 'Lon']].values.tolist() for date, group in df.groupby('Datetime')}
m = folium.Map(location=[4.5, 1.0], zoom_start=10)
features = [
{
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': coords,
},
'properties': {'time': date}
}
for date, coords in grouped_data.items()
]
TimestampedGeoJson({'type': 'FeatureCollection', 'features': features}, period='P1D', duration='P1D').add_to(m)
m
which gives you a map and the ability to slow down the visualization by determining the number of frames per second.
Update: Add lines </>
To add the lines, you need to slightly change the code:
import folium
import pandas as pd
from folium.plugins import TimestampedGeoJson
data = {
'Datetime': ['2021-06-01', '2021-06-01', '2021-06-01', '2021-06-02', '2021-06-02', '2021-06-02'],
'Lat': [4.5, 4.8, 4.4, 4.7, 4.6, 4.9],
'Lon': [1.1, 0.8, 0.9, 1.0, 1.2, 1.3],
'Cars': ['Car1', 'Car1', 'Car2', 'Car2', 'Car1', 'Car2']
}
df = pd.DataFrame(data)
grouped_data = df.groupby(['Cars', 'Datetime'])
m = folium.Map(location=[4.6, 1.0], zoom_start=10)
features = []
for (car, date), group in grouped_data:
coords = group[['Lon', 'Lat']].values.tolist()
if len(coords) > 1:
feature = {
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': coords,
},
'properties': {
'times': [date]*len(coords),
'icon': 'circle',
'iconstyle': {
'fillColor': 'red',
'fillOpacity': 0.6,
'stroke': 'false',
'radius': 6
},
'id': car
}
}
features.append(feature)
TimestampedGeoJson(
{'type': 'FeatureCollection', 'features': features},
period='P1D',
duration='P1D',
add_last_point=True,
auto_play=False,
loop=False,
max_speed=1,
loop_button=True,
date_options='YYYY-MM-DD',
time_slider_drag_update=True
).add_to(m)
m.save('timeline_map.html')
m
Which will give somthiong like this: