Hermoine
Hermoine

Reputation: 73

having a route between two gps coordinates

Good Evening, I have gps coordinates for each trip and i'm trying to have a line between each point for each trip.. I'm using this code, but still doesn't work , if i delete groupby(id) it works but i get a line also between points from not the same tripId ..

tooltip = "Click me!"
for i in range(11):
    folium.Marker(df.groupby('id')
        [df['latitude'][i],df['longitude'][i]], popup=df['id'][i], tooltip=tooltip ).add_to(map)
    
    route = folium.PolyLine(df.groupby('id')
        [[df['latitude'][i],df['longitude'][i]],[df['latitude'][i+1],df['longitude'][i+1]]],
        tooltip = "trip"  ).add_to(map)

my dataframe looks like that :

    longitude   latitude    id
0   5.184529    52.032471   66168
1   5.184513    52.032047   66168
2   5.184468    52.031559   66168
7   5.183908    52.027328   66168
8   5.175724    52.084732   89751
9   5.175513    52.084743   89751
10  5.174866    52.084713   89751

Upvotes: 0

Views: 605

Answers (1)

RJ Adriaansen
RJ Adriaansen

Reputation: 9649

I suggest separating adding the polylines and the markers to the map. Markers can be added individually, the polylines as lists of geolocations. Since the latter needs to be clustered by id, it makes sense to add them per group, after the groupby:

import pandas as pd
import folium
import io

data = '''    longitude   latitude    id
0   5.184529    52.032471   66168
1   5.184513    52.032047   66168
2   5.184468    52.031559   66168
7   5.183908    52.027328   66168
8   5.175724    52.084732   89751
9   5.175513    52.084743   89751
10  5.174866    52.084713   89751'''

df = pd.read_csv(io.StringIO(data), sep='\s\s+')

tooltip = "Click me!"
m = folium.Map(location=[52.031559, 5.184468],
              zoom_start=15)

for index, row in df.iterrows():
    folium.Marker([row['latitude'], row['longitude']],
                        popup=row['id'],
                        tooltip=tooltip
                       ).add_to(m)
    
for index, row in df.groupby('id',as_index=False)[['latitude','longitude']].agg(list).iterrows():
    loc = list(zip(row.latitude, row.longitude))
    folium.PolyLine(loc, tooltip = "trip").add_to(m)

Upvotes: 1

Related Questions