### Installation Source: https://github.com/mthh/routingpy/blob/master/docs/index.rst Instructions on how to install the routingpy library using pip. ```APIDOC ## Installation ### Description Install the routingpy library using pip. ### Command ```bash pip install routingpy ``` ``` -------------------------------- ### Install pre-commit hook Source: https://github.com/mthh/routingpy/blob/master/CONTRIBUTING.md Install the pre-commit hook to automatically format and lint code before each commit. ```bash # From the root of your git project poetry run pre-commit install ``` -------------------------------- ### Install routingpy from source Source: https://github.com/mthh/routingpy/blob/master/README.rst Install the latest version of routingpy directly from its GitHub repository using pip. ```bash pip install git+https://github.com/mthh/routingpy.git ``` -------------------------------- ### Install routingpy with pip Source: https://github.com/mthh/routingpy/blob/master/README.rst Install routingpy using pip. This is a standard method for installing Python packages. ```bash pip install routingpy ``` -------------------------------- ### Get Router by Name Source: https://github.com/mthh/routingpy/blob/master/docs/index.rst Demonstrates how to get a router instance by its name. ```APIDOC ## Get Router by Name ### Description This function retrieves a router instance based on its registered name. ### Function `routingpy.routers.get_router_by_name(name, **options)` ### Parameters - **name** (str) - Required - The name of the router to retrieve (e.g., 'google', 'graphhopper'). - **options** - Optional - Additional keyword arguments to configure the router. ``` -------------------------------- ### Install routingpy with Poetry Source: https://github.com/mthh/routingpy/blob/master/README.rst Use Poetry to add routingpy to your project dependencies. This is the recommended installation method. ```bash poetry add routingpy ``` -------------------------------- ### Install development dependencies with Poetry Source: https://github.com/mthh/routingpy/blob/master/CONTRIBUTING.md Install all necessary development dependencies using Poetry. This includes linters and testing tools. ```bash # From the root of your git project poetry install --with dev ``` -------------------------------- ### Multi-Provider Routing Example Source: https://github.com/mthh/routingpy/blob/master/README.rst Demonstrates calculating directions, isochrones, and matrices using multiple routing providers (ORS, Graphhopper, MapboxOSRM) with their respective profiles. Ensure you have the necessary API keys. ```python from routingpy import Graphhopper, ORS, MapboxOSRM from shapely.geometry import Polygon # Define the clients and their profile parameter apis = ( (ORS(api_key='ors_key'), 'cycling-regular'), (Graphhopper(api_key='gh_key'), 'bike'), (MapboxOSRM(api_key='mapbox_key'), 'cycling') ) # Some locations in Berlin coords = [[13.413706, 52.490202], [13.421838, 52.514105], [13.453649, 52.507987], [13.401947, 52.543373]] for api in apis: client, profile = api route = client.directions(locations=coords, profile=profile) print("Direction - {}: Duration: {} Distance: {}".format(client.__class__.__name__, route.duration, route.distance)) isochrones = client.isochrones(locations=coords[0], profile=profile, intervals=[600, 1200]) for iso in isochrones: print("Isochrone {} secs - {}: Area: {} sqm".format(client.__class__.__name__, iso.interval, Polygon(iso.geometry).area)) matrix = client.matrix(locations=coords, profile=profile) print("Matrix - {}: Durations: {} Distances: {}".format(client.__class__.__name__, matrix.durations, matrix.distances)) ``` -------------------------------- ### Run tests with pytest Source: https://github.com/mthh/routingpy/blob/master/CONTRIBUTING.md Execute the project's test suite to ensure everything is functioning correctly after setup. ```bash # From the root of your git project pytest -v ``` -------------------------------- ### Valhalla Basic Directions Source: https://context7.com/mthh/routingpy/llms.txt Calculates a simple route between multiple waypoints using the Valhalla routing engine with the 'auto' profile. This is a basic usage example. ```python from routingpy import Valhalla client = Valhalla() # Uses public OSM Valhalla server # Simple route with multiple waypoints coords = [ [13.413706, 52.490202], # Start [13.421838, 52.514105], # Via point [13.453649, 52.507987], # Via point [13.401947, 52.543373], # End ] # Basic directions request route = client.directions( locations=coords, profile='auto', # Options: auto, bicycle, bus, pedestrian, motor_scooter, motorcycle ) print(f"Total distance: {route.distance} meters") print(f"Total duration: {route.duration} seconds") print(f"Geometry points: {len(route.geometry)}") ``` -------------------------------- ### Import necessary libraries Source: https://github.com/mthh/routingpy/blob/master/examples/compare_providers.ipynb Imports required libraries for plotting, data manipulation, and geospatial operations. Ensure you have these installed. ```python from itertools import chain from matplotlib import pyplot as plt import pandas as pd import geopandas as gpd import random from shapely.geometry import box, Point, LineString, Polygon, MultiPolygon import contextily as cx from routingpy.routers import get_router_by_name BASEMAP_SOURCE = cx.providers.CartoDB.Positron HEX_ALPHA = "4F" POINT_PLOT_KWDS = {"marker": "D", "color": "black", "markersize": 20} plt.rcParams['figure.dpi'] = 50 ``` -------------------------------- ### OpenTripPlanner V2 Basic Transit Routing Source: https://context7.com/mthh/routingpy/llms.txt Get multimodal transit directions using OpenTripPlanner V2. Specify modes, date, and time for routing. arrive_by=False means depart at the specified time. ```python from routingpy import OpenTripPlannerV2 import datetime # Local OTP instance client = OpenTripPlannerV2(base_url='http://localhost:8080') coords = [[13.413706, 52.490202], [13.421838, 52.514105]] # Basic transit routing routes = client.directions( locations=coords, profile='WALK,TRANSIT', # Comma-separated modes: WALK, TRANSIT, BUS, RAIL, etc. date=datetime.date(2024, 3, 15), time=datetime.time(8, 30), arrive_by=False, # Depart at specified time num_itineraries=3, ) # Returns Directions with multiple itineraries for i, route in enumerate(routes): print(f"Itinerary {i}: {route.distance}m, {route.duration}s") # Access detailed leg information for leg in route.raw.get('legs', []): print(f" - {leg['mode']}: {leg['distance']}m") ``` -------------------------------- ### Get Directions with Valhalla Source: https://github.com/mthh/routingpy/blob/master/README.rst Calculates directions between multiple locations using the Valhalla routing engine. Requires specifying locations and a profile. ```python from routingpy import Valhalla from pprint import pprint # Some locations in Berlin coords = [[13.413706, 52.490202], [13.421838, 52.514105], [13.453649, 52.507987], [13.401947, 52.543373]] client = Valhalla() route = client.directions(locations=coords, profile='pedestrian') ``` -------------------------------- ### Get Router by Name Source: https://context7.com/mthh/routingpy/llms.txt Dynamically retrieves a router class using its string name. This is useful for flexible provider selection or iterating through multiple providers. ```python from routingpy.routers import get_router_by_name # Get router class by name RouterClass = get_router_by_name("ors") client = RouterClass(api_key='your_api_key') # Available router names: "google", "graphhopper", "ign", "mapbox", "mapbox_osrm", # "mapboxosrm", "openrouteservice", "ors", "osrm", "valhalla", # "opentripplanner", "opentripplanner_v2", "otp", "otp_v2" # Example: iterate through multiple providers providers = [ ("valhalla", None, "pedestrian"), ("ors", "your_ors_key", "foot-walking"), ("graphhopper", "your_gh_key", "foot"), ] coords = [[13.413706, 52.490202], [13.421838, 52.514105]] for provider_name, api_key, profile in providers: RouterClass = get_router_by_name(provider_name) if api_key: client = RouterClass(api_key=api_key) else: client = RouterClass() route = client.directions(locations=coords, profile=profile) print(f"{provider_name}: {route.distance}m in {route.duration}s") ``` -------------------------------- ### OpenRouteService Directions: Basic Usage Source: https://context7.com/mthh/routingpy/llms.txt Get basic driving directions using OpenRouteService. Ensure you have your API key and coordinates. ```python from routingpy import ORS client = ORS(api_key='your_ors_api_key') coords = [[8.681495, 49.41461], [8.687872, 49.420318]] # Basic directions route = client.directions( locations=coords, profile='driving-car', ) ``` -------------------------------- ### Mapbox OSRM Directions: Basic Usage Source: https://context7.com/mthh/routingpy/llms.txt Get basic directions using Mapbox OSRM with specified coordinates and profile. Supported profiles include driving-traffic, driving, walking, and cycling. ```python from routingpy import MapboxOSRM client = MapboxOSRM(api_key='your_mapbox_api_key') coords = [[13.413706, 52.490202], [13.421838, 52.514105], [13.453649, 52.507987]] # Basic directions route = client.directions( locations=coords, profile='driving', ) ``` -------------------------------- ### OSRM Directions Basic Source: https://context7.com/mthh/routingpy/llms.txt Get driving directions using a local or public OSRM instance. The profile is often encoded in the base_url for FOSSGIS instances. ```python from routingpy import OSRM # Public FOSSGIS OSRM instance (bike profile encoded in URL) client = OSRM(base_url='https://routing.openstreetmap.de/routed-bike') # Or local instance # client = OSRM(base_url='http://localhost:5000') coords = [[13.413706, 52.490202], [13.421838, 52.514105]] route = client.directions( locations=coords, profile='driving', # Note: FOSSGIS instances encode profile in base_url alternatives=3, steps=True, geometries='geojson', overview='full', annotations=True, continue_straight=True, ) ``` -------------------------------- ### Transit Routing Source: https://context7.com/mthh/routingpy/llms.txt Get transit directions specifying transit modes and routing preferences. Arrival time can be used instead of departure time. ```python route = client.directions( locations=coords, profile='transit', transit_mode=['bus', 'subway', 'train'], transit_routing_preference='fewer_transfers', arrival_time=departure_timestamp, ) ``` -------------------------------- ### Build documentation Source: https://github.com/mthh/routingpy/blob/master/CONTRIBUTING.md Build the project's documentation locally. The output will be in the `build/html` directory. ```bash # From the root of your git project cd docs make html ``` -------------------------------- ### Create and activate a virtual environment Source: https://github.com/mthh/routingpy/blob/master/CONTRIBUTING.md Set up a Python virtual environment for the project. Ensure Python 3.9 or higher is used. ```bash # From the root of your git project python3 -m venv .venv source .venv/bin/activate ``` -------------------------------- ### Initialize Router Clients Source: https://context7.com/mthh/routingpy/llms.txt Demonstrates initializing various router clients with and without API keys. Use this to set up connections to different routing services. ```python from routingpy import Valhalla, ORS, Graphhopper, MapboxOSRM, Google # Valhalla - uses public OSM server by default (no API key needed) valhalla_client = Valhalla() # OpenRouteService - requires API key ors_client = ORS(api_key='your_ors_api_key') # GraphHopper - requires API key gh_client = Graphhopper(api_key='your_graphhopper_api_key') # Mapbox OSRM - requires API key mapbox_client = MapboxOSRM(api_key='your_mapbox_api_key') # Google Maps - requires API key google_client = Google(api_key='your_google_api_key') # Local Valhalla instance local_valhalla = Valhalla(base_url='http://localhost:8002') # Coordinates in Berlin [longitude, latitude] coords = [[13.413706, 52.490202], [13.421838, 52.514105]] # Get directions - same interface for all providers route = valhalla_client.directions(locations=coords, profile='pedestrian') print(f"Distance: {route.distance} meters, Duration: {route.duration} seconds") print(f"Distance in km: {route.km}, Distance in miles: {route.mi}") print(f"Route geometry: {route.geometry[:3]}...") # [[lon, lat], ...] ``` -------------------------------- ### Initialize Valhalla API Client Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Sets up the Valhalla API client. Defaults to a public instance if no base_url is provided. ```python # defaults to https://valhalla1.openstreetmap.de api = rp.Valhalla() isochrones = api.isochrones(locations=coordinates[0], profile='auto', intervals=[100,200]) ``` -------------------------------- ### Configure router clients Source: https://github.com/mthh/routingpy/blob/master/examples/compare_providers.ipynb Sets up a dictionary of router configurations, including API keys, display names, routing profiles, colors, and isochrone support. Comment out providers you do not wish to use. ```python routers = { 'ors': { 'api_key': '', 'display_name': 'OpenRouteService', 'profile': 'driving-car', 'color': '#b5152b', 'isochrones': True }, 'mapbox_osrm': { 'api_key': '', 'display_name': 'MapBox (OSRM)', 'profile': 'driving', 'color': '#ff9900', 'isochrones_profile': 'mapbox/driving', 'isochrones': True }, 'google': { 'api_key': '', 'display_name': 'Google', 'profile': 'driving', 'color': '#ff33cc', 'isochrones': False }, 'graphhopper': { 'api_key': '', 'display_name': 'GraphHopper', 'profile': 'car', 'color': '#417900', 'isochrones': True }, 'heremaps': { 'api_key': '', 'display_name': 'HereMaps', 'profile': 'car', 'color': '#8A2BE2', 'isochrones': True } } ``` -------------------------------- ### Initialize Valhalla API Client with Custom URL Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Sets up the Valhalla API client using a custom base URL, useful for self-hosted instances. ```python valhalla_public_url = "https://valhalla1.openstreetmap.de" api = rp.Valhalla(base_url=valhalla_public_url) expansions = api.expansion(locations=coordinates[0], profile='auto', intervals=[200], expansion_properties=["durations"]) ``` -------------------------------- ### Initialize RoutingPy with OpenRouteService API Key Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Sets up the OpenRouteService API client. Ensure you have a valid API key from openrouteservice.org. ```python import routingpy as rp from shapely.geometry import LineString, Point, Polygon from matplotlib import pyplot as plt import geopandas as gpd import contextily as cx from pprint import pprint BASEMAP_SOURCE = cx.providers.CartoDB.Positron coordinates = [[8.512516, 47.380742], [8.557835, 47.359467]] plt.rcParams['figure.dpi'] = 50 # Create your own API key at https://openrouteservice.org/sign-up key_ors = "" api = rp.ORS(api_key=key_ors) route = api.directions(locations=coordinates, profile='driving-car') ``` -------------------------------- ### Connecting to a Local Valhalla Instance Source: https://github.com/mthh/routingpy/blob/master/README.rst Connects to a locally running Valhalla instance by specifying the `base_url`. The `api_key` is not necessary for local instances. ```python from routingpy import Valhalla # no trailing slash, api_key is not necessary client = Valhalla(base_url='http://localhost:8088/v1') ``` -------------------------------- ### Initialize HereMaps API Client and Calculate Matrix Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Sets up the HereMaps API client and calculates a travel time and distance matrix between specified coordinates. Requires a HereMaps API key. ```python # Create your own API key at https://developer.here.com/?create=Freemium-Basic&keepState=true&step=account here_key = "" api = rp.HereMaps(api_key=here_key) matrix = api.matrix(locations=coordinates, profile='car') pprint(matrix.durations) pprint(matrix.raw) ``` -------------------------------- ### Visualize Routing Graph Expansion with Valhalla Source: https://context7.com/mthh/routingpy/llms.txt Generates and visualizes the routing graph expansion for debugging purposes using the Valhalla API. Allows specifying expansion properties and intervals. ```python from routingpy import Valhalla client = Valhalla() location = [13.413706, 52.490202] # Get expansion graph expansion = client.expansion( locations=location, profile='auto', intervals=[300], # 5 minutes interval_type='time', skip_opposites=True, # Don't include reverse edges expansion_properties=['duration', 'distance', 'cost', 'edge_id'], ) print(f"Number of edges: {len(expansion)}") for edge in list(expansion)[:5]: # First 5 edges print(f"Edge geometry: {edge.geometry}") print(f"Duration: {edge.duration}, Distance: {edge.distance}") ``` -------------------------------- ### Calculating Isochrones from Multiple Routers Source: https://github.com/mthh/routingpy/blob/master/examples/compare_providers.ipynb Calculates isochrones for given locations using different routing services. Handles variations in API parameters like 'intervals' and 'buckets' for Graphhopper. Requires setup of router configurations and API keys. ```python dict_ = {"router": [], "interval": [], "center": []} isos = [] geometries = [] for router in routers: if routers[router]["isochrones"]: for location in input_isochrones: api = get_router_by_name(router)(api_key=routers[router]['api_key']) # Mapbox decided to call their isochrones profiles different from their directions profiles profile = routers[router].get('isochrones_profile') or routers[router]['profile'] if router == 'graphhopper': isochrones = api.isochrones( profile=profile, # note: graphhopper just takes one interval which # can be split into equal buckets with the below parameter intervals=[600], buckets=3, locations=location ) else: isochrones = api.isochrones( profile=profile, intervals=[120,300,420,600], locations=location, ) isos.append({"router": router, "iso": isochrones}) for idx, isochrone in reversed(list(enumerate(isochrones))): dict_["router"].append(router) dict_["interval"].append(isochrone.interval) dict_["center"].append(isochrone.center) if router == "heremaps": geometries.append(MultiPolygon([Polygon(X) for X in isochrone.geometry])) else: geometries.append(Polygon(isochrone.geometry)) print("Calulated {}".format(router)) isochrones_df = gpd.GeoDataFrame(dict_, geometry=geometries, crs="EPSG:4326").to_crs("EPSG:3857") ``` -------------------------------- ### Visualizing Routes on a Map Source: https://github.com/mthh/routingpy/blob/master/examples/compare_providers.ipynb Plots the calculated routes for each router on a separate subplot within a matplotlib figure. It also overlays the starting and ending points for each route. Requires `plt`, `cx`, `routers`, `routes_df`, `input_pairs`, `Point`, and `gpd` to be defined. ```python fig, axs = plt.subplots(3,2, figsize=(15,20)) img, ext = cx.bounds2img(*bbox, ll=True, source=BASEMAP_SOURCE) for idx, router in enumerate(routers): ax = axs.flatten()[idx] _ = ax.imshow(img, extent=ext) routes_df.query(f"router == '{router}'").plot( ax=ax, linewidth=3, color=routers[router]["color"] ) for pair in input_pairs: input_df = gpd.GeoDataFrame(geometry=[Point(x,y) for x,y in pair], crs="EPSG:4326").to_crs("EPSG:3857") input_df.plot(ax=ax, **POINT_PLOT_KWDS) _ = ax.axis("off") ax.set_title(routers[router]['display_name']) fig.tight_layout() ``` -------------------------------- ### Valhalla Advanced Directions with Options Source: https://context7.com/mthh/routingpy/llms.txt Calculates routes with advanced options including preferences, instructions, language, avoidance, departure time, and alternative routes. Handles alternative routes if returned. ```python from routingpy import Valhalla client = Valhalla() # Uses public OSM Valhalla server # Simple route with multiple waypoints coords = [ [13.413706, 52.490202], # Start [13.421838, 52.514105], # Via point [13.453649, 52.507987], # Via point [13.401947, 52.543373], # End ] # Advanced options with preferences and avoidance route = client.directions( locations=coords, profile='auto', preference='shortest', # 'fastest' or 'shortest' instructions=True, # Include turn-by-turn instructions language='de', # Instruction language avoid_locations=[[13.43, 52.51]], # Locations to avoid date_time={'type': 1, 'value': '2024-03-15T08:00'}, # Departure time alternatives=2, # Request alternative routes ) # With alternatives, returns Directions (list-like) object if hasattr(route, '__iter__'): for i, alt_route in enumerate(route): print(f"Route {i}: {alt_route.distance}m, {alt_route.duration}s") ``` -------------------------------- ### Client Class Source: https://github.com/mthh/routingpy/blob/master/docs/index.rst The default client class for making routing requests. ```APIDOC ## Client Class ### Description Provides a default client interface for interacting with routing services. ### Class `routingpy.client_default.Client` ### Initialization `__init__(**kwargs)` - **kwargs** - Keyword arguments passed to the router initialization. ``` -------------------------------- ### Run tests with coverage Source: https://github.com/mthh/routingpy/blob/master/CONTRIBUTING.md Execute tests and generate a code coverage report. This helps identify areas of the code not tested. ```bash # From the root of your git project coverage run --source=routingpy --module pytest ``` -------------------------------- ### Clone the routingpy repository Source: https://github.com/mthh/routingpy/blob/master/CONTRIBUTING.md Clone the repository to your local machine and navigate into the project directory. ```bash git clone https://github.com/mthh/routingpy cd routingpy ``` -------------------------------- ### Configure Global Routing Options Source: https://context7.com/mthh/routingpy/llms.txt Sets default configuration options for all router instances, such as timeouts, retries, and proxies. These defaults can be overridden per instance. ```python from routingpy.routers import options from routingpy import ORS, Valhalla # Set global defaults options.default_timeout = 30 # Seconds options.default_retry_timeout = 60 # Total retry time options.default_retry_over_query_limit = True # Auto-retry on 429 options.default_skip_api_error = False # Raise on API errors options.default_user_agent = 'my-routing-app/1.0' options.default_proxies = {'https': 'http://proxy.example.com:8080'} # All new clients inherit these defaults client1 = Valhalla() client2 = ORS(api_key='your_key') # Override per-instance client3 = ORS( api_key='your_key', timeout=120, retry_over_query_limit=False, skip_api_error=True, requests_kwargs={'proxies': {'https': 'http://other-proxy.com:8080'}}, ) # Check applied settings print(f"User-Agent: {client3.client.headers['User-Agent']}") ``` -------------------------------- ### Plot Expansion Data with Basemap Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Visualizes the expansion lines, colored by duration, and adds a basemap. Only shows lines with durations less than or equal to 200. ```python fig, ax = plt.subplots(1,1, figsize=(10,10)) expansion_df[expansion_df["duration"] <= 200].plot(ax=ax, column="duration", cmap="RdYlGn_r", linewidth=1, alpha=1) start_end.iloc[:-1].plot(ax=ax, color="black", markersize=20) cx.add_basemap(ax=ax, crs="EPSG:3857", source=BASEMAP_SOURCE) _ = ax.axis("off") ``` -------------------------------- ### Configuring Proxies and Error Handling Source: https://github.com/mthh/routingpy/blob/master/README.rst Sets up proxy configurations and error handling options for Graphhopper and ORS clients. These can also be set globally using `routingpy.routers.options`. ```python from routingpy import Graphhopper, ORS from routingpy.routers import options request_kwargs = dict(proxies=dict(https='129.125.12.0')) client = Graphhopper( api_key='gh_key', retry_over_query_limit=False, skip_api_error=True, requests_kwargs=request_kwargs ) # Or alternatively, set these options globally: options.default_proxies = {'https': '129.125.12.0'} options.default_retry_over_query_limit = False options.default_skip_api_error = True ``` -------------------------------- ### Calculate Routing Matrix with RoutingPy Source: https://github.com/mthh/routingpy/blob/master/examples/compare_providers.ipynb Iterates through configured routers, initializes their respective APIs, and calculates a duration matrix for all pairs of locations. Requires input_matrix, routers, and durations to be pre-defined. ```python number_locations = len(input_matrix) from_indices = list(chain.from_iterable([[x] * number_locations for x in range(number_locations)])) to_indices = list(chain.from_iterable([[int(x) for x in range(number_locations)] for _ in range(number_locations)])) for idx, router in enumerate(routers): api = get_router_by_name(router)(api_key=routers[router]['api_key']) all_indices = list(range(len(input_matrix))) matrix = api.matrix( locations=input_matrix, sources=all_indices, destinations=all_indices, profile=routers[router]['profile'] ) print("Calulated {}".format(router)) durations.append(list(chain.from_iterable(matrix.durations))) ``` -------------------------------- ### Compare Routing Providers Source: https://context7.com/mthh/routingpy/llms.txt Compares routing results (directions, isochrones, matrix) across multiple providers like Valhalla, ORS, Graphhopper, and MapboxOSRM for the same query. Handles potential 'NotImplementedError' for unsupported features. ```python from routingpy import Valhalla, ORS, Graphhopper, MapboxOSRM from shapely.geometry import Polygon # Provider configurations with their bike profile names providers = [ (Valhalla(), 'bicycle'), (ORS(api_key='ors_key'), 'cycling-regular'), (Graphhopper(api_key='gh_key'), 'bike'), (MapboxOSRM(api_key='mapbox_key'), 'cycling'), ] coords = [[13.413706, 52.490202], [13.421838, 52.514105], [13.453649, 52.507987], [13.401947, 52.543373]] print("=== Directions Comparison ===") for client, profile in providers: try: route = client.directions(locations=coords, profile=profile) print(f"{client.__class__.__name__}: {route.distance}m, {route.duration}s") except Exception as e: print(f"{client.__class__.__name__}: Error - {e}") print("\n=== Isochrones Comparison ===") for client, profile in providers: try: isochrones = client.isochrones( locations=coords[0], profile=profile, intervals=[600, 1200], ) for iso in isochrones: area = Polygon(iso.geometry).area if iso.geometry else 0 print(f"{client.__class__.__name__} ({iso.interval}s): area={area:.6f}") except NotImplementedError: print(f"{client.__class__.__name__}: Isochrones not supported") except Exception as e: print(f"{client.__class__.__name__}: Error - {e}") print("\n=== Matrix Comparison ===") for client, profile in providers: try: matrix = client.matrix(locations=coords, profile=profile) avg_duration = sum(sum(r) for r in matrix.durations) / (len(coords) ** 2) print(f"{client.__class__.__name__}: avg duration={avg_duration:.0f}s") except NotImplementedError: print(f"{client.__class__.__name__}: Matrix not supported") except Exception as e: print(f"{client.__class__.__name__}: Error - {e}") ``` -------------------------------- ### Valhalla Directions with Custom Waypoints Source: https://context7.com/mthh/routingpy/llms.txt Calculates a route using custom waypoint objects that allow specifying additional constraints like heading and heading tolerance. Demonstrates advanced waypoint configuration. ```python from routingpy import Valhalla client = Valhalla() # Uses public OSM Valhalla server # Simple route with multiple waypoints coords = [ [13.413706, 52.490202], # Start [13.421838, 52.514105], # Via point [13.453649, 52.507987], # Via point [13.401947, 52.543373], # End ] # Using custom waypoints with additional constraints waypoint = Valhalla.Waypoint( position=[13.421838, 52.514105], type='through', # Pass through without stopping heading=120, # Preferred heading in degrees heading_tolerance=10, ) route = client.directions( locations=[[13.413706, 52.490202], waypoint, [13.453649, 52.507987]], profile='bicycle', ) ``` -------------------------------- ### OpenTripPlannerV2 Router Source: https://github.com/mthh/routingpy/blob/master/docs/index.rst Configuration and usage of the OpenTripPlanner v2 routing service. ```APIDOC ## OpenTripPlannerV2 Router ### Description Configuration and methods for using the OpenTripPlanner v2 routing service. ### Class `routingpy.routers.OpenTripPlannerV2` ### Initialization `__init__(api_key: str, api_url: str = None, timeout: int = 60, **kwargs)` - **api_key** (str) - Required - Your OpenTripPlanner v2 API key. - **api_url** (str) - Optional - Custom API endpoint URL. - **timeout** (int) - Optional - Request timeout in seconds. Defaults to 60. - **kwargs** - Additional keyword arguments passed to the options object. ``` -------------------------------- ### Mapbox OSRM Directions: Navigation Options Source: https://context7.com/mthh/routingpy/llms.txt Request directions with navigation-specific options like alternatives, steps, geometries, annotations, exclusions, language, voice instructions, banner instructions, roundabout exits, and approaches. Ensure to check `route.raw` for alternatives. ```python from routingpy import MapboxOSRM client = MapboxOSRM(api_key='your_mapbox_api_key') coords = [[13.413706, 52.490202], [13.421838, 52.514105], [13.453649, 52.507987]] # With navigation options route = client.directions( locations=coords, profile='driving-traffic', alternatives=True, steps=True, geometries='geojson', overview='full', annotations=['duration', 'distance', 'speed', 'congestion'], exclude='toll', language='en', voice_instructions=True, voice_units='metric', banner_instructions=True, roundabout_exits=True, approaches=['unrestricted', 'curb', 'unrestricted'], waypoint_names=['Start', 'Coffee Shop', 'Office'], ) # Access alternatives if route.raw: print(f"Primary route: {route.distance}m") ``` -------------------------------- ### OSRM Directions with Bearings and Radiuses Source: https://context7.com/mthh/routingpy/llms.txt Specify search radius and bearing constraints for each waypoint in OSRM directions. Radiuses are in meters, bearings are in degrees. ```python route = client.directions( locations=coords, profile='driving', radiuses=[100, 100], # Search radius in meters for each waypoint bearings=[[90, 45], [180, 45]], # [bearing, deviation] for each waypoint ) ``` -------------------------------- ### GraphHopper Directions: Detailed Options Source: https://context7.com/mthh/routingpy/llms.txt Calculate routes with detailed options such as instructions, locale, elevation, points_encoded, details, ch_disable, headings, snap_preventions, and curbsides. Note that `ch_disable=True` is required for some advanced options. ```python from routingpy import Graphhopper client = Graphhopper(api_key='your_graphhopper_api_key') coords = [[13.413706, 52.490202], [13.421838, 52.514105]] # With detailed options route = client.directions( locations=coords, profile='car', instructions=True, locale='de', elevation=True, points_encoded=False, details=['street_name', 'time', 'distance', 'max_speed'], ch_disable=True, headings=[90, 270], snap_preventions=['motorway', 'ferry'], curbsides=['right', 'right'], ) ``` -------------------------------- ### Plot Route with Basemap using Matplotlib and Contextily Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Visualizes the calculated route and start/end points on a map. Adds a basemap using contextily. ```python fig, ax = plt.subplots(1,1, figsize=(10,10)) start_end.plot(ax=ax, color="red") route_line.plot(ax=ax, color="red", linewidth=3, alpha=0.5) cx.add_basemap(ax=ax, crs="EPSG:3857", source=BASEMAP_SOURCE) _ = ax.axis("off") ``` -------------------------------- ### Valhalla Isochrones with Advanced Options Source: https://context7.com/mthh/routingpy/llms.txt Configure isochrone calculations with custom colors, avoidance areas, and specific date/time preferences. The 'auto' profile attempts to select the best mode. ```python # With colors and advanced options isochrones = client.isochrones( locations=location, profile='auto', intervals=[600, 1200, 1800], colors=['ff0000', '00ff00', '0000ff'], # Red, green, blue preference='shortest', avoid_locations=[[13.42, 52.50]], date_time={'type': 1, 'value': '2024-03-15T08:00'}, ) # Access raw GeoJSON response print(isochrones.raw['features'][0]['geometry']['type']) ``` -------------------------------- ### Directions with WayPoint Class Source: https://context7.com/mthh/routingpy/llms.txt Use the WayPoint class to specify intermediate points, including 'via' points that are not stops. Set stopover=False for via points. ```python via_point = Google.WayPoint( position=[13.421838, 52.514105], waypoint_type='coords', stopover=False, # Pass through without stopping ) route = client.directions( locations=[[13.413706, 52.490202], via_point, [13.401947, 52.543373]], profile='driving', ) ``` -------------------------------- ### Directions with Traffic and Time Source: https://context7.com/mthh/routingpy/llms.txt Calculate driving directions with specified departure time and traffic model. Ensure departure_time is an integer timestamp. ```python import time departure_timestamp = int(time.time()) + 3600 # 1 hour from now route = client.directions( locations=coords, profile='driving', alternatives=True, avoid=['tolls', 'highways'], language='en', units='metric', departure_time=departure_timestamp, traffic_model='best_guess', # best_guess, pessimistic, optimistic ) ``` -------------------------------- ### Default Options Object Source: https://github.com/mthh/routingpy/blob/master/docs/index.rst Details about the default options object used for configuring routers. ```APIDOC ## Default Options Object ### Description This section describes the `options` object, which holds default configuration settings applicable to various routers. ### Class `routingpy.routers.options` ### Members - **`api_key`** (str) - API key for the routing service. - **`api_url`** (str) - Base URL for the routing service API. - **`timeout`** (int) - Request timeout in seconds. - **`retry_over_query_limit`** (bool) - Whether to retry requests when the query limit is exceeded. ``` -------------------------------- ### Fetching Directions from Multiple Routers Source: https://github.com/mthh/routingpy/blob/master/examples/compare_providers.ipynb Iterates through a list of routers, fetches directions for predefined coordinate pairs using the `directions` endpoint, and stores the distance, duration, and geometry. Requires `get_router_by_name`, `routers`, `input_pairs`, `Point`, `LineString`, and `gpd` to be defined. ```python dict_ = {"router": [], "distance": [], "duration": []} geometries = [] for router in routers: api = get_router_by_name(router)(api_key=routers[router]['api_key']) for coords_pair in input_pairs: # just from A to B without intermediate points route = api.directions( profile=routers[router]['profile'], locations=coords_pair ) # Access the route properties with .geometry, .duration, .distance distance, duration = route.distance / 1000, int(route.duration / 60) dict_["router"].append(router) dict_["distance"].append(distance) dict_["duration"].append(duration) geometries.append(LineString(route.geometry)) print("Calulated {}".format(router)) routes_df = gpd.GeoDataFrame(dict_, geometry=geometries, crs="EPSG:4326").to_crs("EPSG:3857") ``` -------------------------------- ### OpenRouteService Directions: Alternative Routes Source: https://context7.com/mthh/routingpy/llms.txt Calculate alternative routes with specified sharing factors, target counts, and weight factors. The result is a Directions object containing multiple routes. ```python from routingpy import ORS client = ORS(api_key='your_ors_api_key') coords = [[8.681495, 49.41461], [8.687872, 49.420318]] # Alternative routes route = client.directions( locations=coords, profile='driving-car', alternative_routes={ 'share_factor': 0.6, 'target_count': 3, 'weight_factor': 1.4, }, ) # Returns Directions object with multiple routes for i, alt in enumerate(route): print(f"Alternative {i}: {alt.distance}m, {alt.duration}s") ``` -------------------------------- ### Calculate Isochrones with Valhalla Source: https://github.com/mthh/routingpy/blob/master/README.rst Calculates isochrones for a given location using the Valhalla routing engine. Requires specifying a single location, a profile, and time intervals. ```python isochrones = client.isochrones(locations=coords[0], profile='pedestrian', intervals=[600, 1200]) ``` -------------------------------- ### Create GeoDataFrame for Expansion Data Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Converts Valhalla expansion data, including durations and geometry, into a GeoDataFrame for plotting. ```python expansion_df = gpd.GeoDataFrame( {"id": [x for x in range(len(expansions))], "duration": [x.duration for x in expansions]}, geometry=[LineString(X.geometry) for X in expansions], crs="EPSG:4326", ).to_crs("EPSG:3857") ``` -------------------------------- ### Create GeoDataFrames for Route and Start/End Points Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Converts route geometry and coordinates into GeoDataFrames for plotting. Reprojects to EPSG:3857 for better map display. ```python start_end = gpd.GeoDataFrame(geometry=[Point(x,y) for x,y in coordinates], crs="EPSG:4326").to_crs("EPSG:3857") route_line = gpd.GeoDataFrame(geometry=[LineString(route.geometry)], crs="EPSG:4326").to_crs("EPSG:3857") ``` -------------------------------- ### OverQueryLimit Exception Source: https://github.com/mthh/routingpy/blob/master/docs/index.rst Exception raised when the API query limit is exceeded. ```APIDOC ## OverQueryLimit Exception ### Description Raised when the number of requests exceeds the API's query limit. ### Class `routingpy.exceptions.OverQueryLimit` ### Inheritance Inherits from `RouterError`. ``` -------------------------------- ### OpenTripPlanner V2 Directions API Source: https://context7.com/mthh/routingpy/llms.txt Provides multimodal transit directions using OpenTripPlanner's GraphQL API. Supports various transit modes and routing preferences. ```APIDOC ## OpenTripPlanner V2 Directions Get multimodal transit directions using OpenTripPlanner's GraphQL API. ### Method POST ### Endpoint /otp/v2/routers/{routerId}/plan ### Parameters #### Query Parameters - **locations** (list of lists or strings) - Required - Origin and destination coordinates or place names. - **profile** (string) - Required - Comma-separated list of transit modes (e.g., 'WALK,TRANSIT,BUS'). - **date** (date) - Required - The date for the trip. - **time** (time) - Required - The time for the trip. - **arrive_by** (boolean) - Optional - If true, the time is an arrival time; otherwise, it's a departure time. Defaults to false. - **num_itineraries** (integer) - Optional - The number of alternative itineraries to return. ### Request Example ```python from routingpy import OpenTripPlannerV2 import datetime client = OpenTripPlannerV2(base_url='http://localhost:8080') coords = [[13.413706, 52.490202], [13.421838, 52.514105]] routes = client.directions( locations=coords, profile='WALK,TRANSIT', date=datetime.date(2024, 3, 15), time=datetime.time(8, 30), arrive_by=False, num_itineraries=3, ) ``` ### Response #### Success Response (200) - **routes** (list) - A list of itinerary objects, each containing route details. - **distance** (number) - Total distance of the itinerary in meters. - **duration** (number) - Total duration of the itinerary in seconds. - **legs** (list) - Detailed leg information for the itinerary. #### Response Example ```json { "routes": [ { "distance": 5000, "duration": 600, "legs": [ { "mode": "WALK", "distance": 1000, "duration": 120 }, { "mode": "BUS", "distance": 4000, "duration": 480 } ] } ] } ``` ``` -------------------------------- ### GraphHopper Directions: Basic Usage Source: https://context7.com/mthh/routingpy/llms.txt Compute basic routes using GraphHopper with specified coordinates and profile. Available profiles include car, bike, foot, and more. ```python from routingpy import Graphhopper client = Graphhopper(api_key='your_graphhopper_api_key') coords = [[13.413706, 52.490202], [13.421838, 52.514105]] # Basic directions route = client.directions( locations=coords, profile='car', ) print(f"Distance: {route.distance}m, Duration: {route.duration}s") ``` -------------------------------- ### Plot Isochrones with Basemap Source: https://github.com/mthh/routingpy/blob/master/examples/basic_examples.ipynb Visualizes the isochrone polygons with different colors based on their ID and adds a basemap. ```python fig, ax = plt.subplots(1,1, figsize=(10,10)) isochrone_df.plot(ax=ax, column="id", cmap="RdYlGn", linewidth=0, alpha=0.2) isochrone_df.plot(ax=ax, column="id", cmap="RdYlGn", linewidth=2, alpha=1, facecolor="none") start_end.iloc[:-1].plot(ax=ax, color="black", markersize=45) cx.add_basemap(ax=ax, crs="EPSG:3857", source=BASEMAP_SOURCE) _ = ax.axis("off") ``` -------------------------------- ### OpenRouteService Directions: Advanced Options Source: https://context7.com/mthh/routingpy/llms.txt Request directions with advanced options like format, preference, geometry, elevation, extra info, attributes, and specific vehicle parameters. Note the available profiles and options for customization. ```python from routingpy import ORS client = ORS(api_key='your_ors_api_key') coords = [[8.681495, 49.41461], [8.687872, 49.420318]] # Advanced request with all options route = client.directions( locations=coords, profile='driving-hgv', format='geojson', preference='fastest', language='en', geometry=True, instructions=True, elevation=True, extra_info=['steepness', 'surface', 'waytype'], attributes=['avgspeed', 'percentage'], options={ 'vehicle_type': 'hgv', 'profile_params': { 'restrictions': { 'height': 3.5, 'weight': 20, } }, 'avoid_features': ['ferries', 'tollways'], }, ) ```