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!
@staticmethod
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 = requests.post('https://api.openrouteservice.org/v2/directions/driving-car', json=body, headers=headers)
return response.json()
@staticmethod
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:
features.append(MapPoint.from_geo_point(start))
if end:
features.append(MapPoint.from_geo_point(end))
if start and end:
route = self.get_route([start.lon, start.lat], [end.lon, end.lat])
distance = round(route['routes'][0]['summary']['distance'] / 1000 * 2, 0)
color = Color.black()
route_feature = self.generate_feature(route, color.hex)
features.append(route_feature)
return MapResult(features)