Returning a .gpx file for directions

Hello! I am at the moment developing a web application on which users can calculate small instance TSP from coordinates or adresses they upload and retreive the shortest route between them all. The last functionality I want to include is the ability to download a .gpx file of the directions of the route so a user can use the route in his GPS or navigation system etc.

The problem I encounter is that even though the route is plotted correctly on the map in my application, I somehow cannot convert it to a .gpx file. Everytime I convert it, in the .gpx file it only shows the main points to be visited and not every road and point in the directions, so that in the end only the flying distance is displayed in a GPS.

Below I provided a code snipped. I will be very thankful if anyone could help me as Im doing this project for my masters thesis :slight_smile:

#plotting the best route calculated by a genetic algorithm
response_ga = client.directions(coordinates = updated_list_ga_ors, profile = profile, format=“geojson”)
route_coords_ga = response_ga[“features”][0][“geometry”][“coordinates”]

route_coords_ga = [[coord[1], coord[0]] for coord in route_coords_ga]

best_ga_route = folium.PolyLine(locations=route_coords_ga, color="red")

m.add_child(best_ga_route)

    # Generate GPX file
gpx = gpxpy.gpx.GPX()
gpx_track = gpxpy.gpx.GPXTrack()
gpx.tracks.append(gpx_track)
gpx_segment = gpxpy.gpx.GPXTrackSegment()
gpx_track.segments.append(gpx_segment)

for point in updated_list_ga_ors:
    gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(latitude=point[1], longitude=point[0]))

# Get the GPX data as a string
gpx_data = gpx.to_xml()

iframe = m.get_root()._repr_html_()

# Store GPX data as a session variable
session["gpx_data"] = gpx_data

Hey,

did you know that the openrouteservice can return gpx data directly?

If this doesn’t work for you, I’m afraid we can’t help any more than that. Try contacting the gpxpy-community directly or ask via a general purpose python help forum, such as stackoverflow.

Best regards

1 Like

@jschnell thanks a lot!
How do I adress the API correctly to return me a plotted route in gpx data though? :slight_smile:

Should be fairly easy. It has it’s own api url:
https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/gpx/post

If you’re using the python client have a look at the docs and the “format” parameter:
https://openrouteservice-py.readthedocs.io/en/latest/#module-openrouteservice.directions

@Jules sorry but could you maybe explain it base on my code? Im a total noob and learned everything I know through youtube tutorials. I think the documentation is a bit too advanced for me. :confused:

This is my code meanwhile:

What I currently can do is retreiving the coordinates of the different points I upload to my application. But I still dont get how I can export the whole route as a gpx and not only the single points. I am now trying to do it via the instruction waypoints, which would be a mediocre result for me because, ultimately I want the user to be able to upload the gox to different devices and tools.

#get the cordinates for teh route (only the waypoints

response_ga = client.directions(coordinates = updated_list_ga_ors, profile = profile, format=“geojson”)
route_coords_ga = response_ga[“features”][0][“geometry”][“coordinates”]

    route_coords_ga = [[coord[1], coord[0]] for coord in route_coords_ga]

    waypoints = list(dict.fromkeys(reduce(operator.concat, list(map(lambda step: step["way_points"], response_ga["features"][0]["properties"]["segments"][0]["steps"] )))))
    directions_ga = folium.PolyLine(locations=[list(reversed(response_ga["features"][0]["geometry"]["coordinates"][index])) for index in waypoints], color = "green")
    best_ga_route = folium.PolyLine(locations=route_coords_ga, color="red")

    # Extract waypoints from the response_ga object
    
    waypoints = []
    for step in response_ga["features"][0]["properties"]["segments"][0]["steps"]:
        waypoints.extend(step["way_points"])

    instructions = []
    for step in response_ga["features"][0]["properties"]["segments"][0]["steps"]:
        instructions.extend(step["instruction"])
        
    # Add markers to the map for each waypoint
    for i, step in enumerate(response_ga["features"][0]["properties"]["segments"][0]["steps"]):
        lat, lon = reversed(response_ga["features"][0]["geometry"]["coordinates"][waypoints[i]])
        instruction = step["instruction"]
        marker_coords = [lat, lon]
        popup_text = f"Coordinates: {lat}, {lon}<br>Instruction: {instruction}"
        folium.Marker(location=marker_coords, icon=folium.Icon(color='green'), popup=popup_text).add_to(m)

    #m.add_child(directions_ga)
    m.add_child(best_ga_route)
    m.add_child(marker_group)

I hope you get what I mean. Otherwise I am kind of screwed :/. Sorry for being annoying. I thinks once I understood the whole concept of your API and how to address it, Ill be able to figure it out.

Thanks in advance!

response_ga = client.directions(coordinates = updated_list_ga_ors, profile = profile, format=“geojson”)

response_gpx = client.directions(coordinates = updated_list_ga_ors, profile = profile, format=“gpx”)

and you get the response as gpx

1 Like