Snippet Wednesday - Routing & Navigation 🚗

Hi all,

For this first Snippet Wednesday I wanted to share something I have worked on before and @matthijs Also contributed on.
What if you’d like to include some navigation functionalities in your VIKTOR application? The easiest method is to include one of multiple choices of public routing API’s. In this case we used the one of Openrouteservice. So if you just use their service to create your own free API key you can use the snippet below to include the navigation between two points in your app!

    def get_route(start, end) -> dict:
        body = {"coordinates": [start, end]}
        headers = {
            'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',
            'Authorization': 'YOUR API KEY',
            'Content-Type': 'application/json; charset=utf-8'
        response ='', json=body, headers=headers)
        return response.json()

    def generate_feature(route: dict, color=None):
        geometry = route['routes'][0]['geometry']
        coords_geojson = polyline.decode(geometry, geojson=True)
        coords_mappoints = [MapPoint(coords[1], coords[0]) for coords in coords_geojson]
        my_feature = MapPolyline(*coords_mappoints)

        return my_feature

    @MapView('Calculation', duration_guess=2)
    def get_map(self, params, **kwargs):
        features = []
        start, end = params.start, params.end

        if start:
        if end:
        if start and end:
            route = self.get_route([start.lon,], [end.lon,])
            distance = round(route['routes'][0]['summary']['distance'] / 1000 * 2, 0)
            color =
            route_feature = self.generate_feature(route, color.hex)

        return MapResult(features)


Hi all,

@kschmidt pointed my attention towards the post request in this snippet. A he rightfully pointed out, post / get methods without timeout could end up getting stuck indefinitely. It is therefore good practice to include a timeout parameter in the request (a couple of seconds is in this case more than enough).

More information can be found in the request docs

Happy coding!

1 Like