Welcome to routingpy’s documentation!

Documentation:

https://routingpy.readthedocs.io/

Source Code:

https://github.com/mthh/routingpy

Issue Tracker:

https://github.com/mthh/routingpy/issues

PyPI:

https://pypi.org/project/routingpy

MyBinder Interactive Examples:

https://mybinder.org/v2/gh/mthh/routingpy/master?filepath=examples

routingpy is a Python 3 client for a lot of popular web routing services.

Using routingpy you can easily request directions, isochrones and matrices from many reliable online providers in a consistent fashion. Base parameters are the same for all services, while still preserving each service’s special parameters (for more info, please look at our README). Take a look at our Examples to see how simple you can compare routes from different providers.

routingpy is tested against CPython 3.9, 3.10, 3.11, 3.12, 3.13 and 3.14 as well as PyPy3 version 3.9 and 3.10.

Installation

pip install routingpy

Routers

Every routing service below has a separate module in routingpy.routers, which hosts a class abstracting the service’s API. Each router has at least a directions method, many offer additionally matrix and/or isochrones methods. Other available provider endpoints are allowed and generally encouraged. However, please refer to our contribution guidelines for general instructions.

The requests are handled via a client class derived from routingpy.client_base.BaseClient.

routingpy’s dogma is, that all routers expose the same mandatory arguments for common methods in an attempt to be consistent for the same method across different routers. Unlike other collective libraries, we additionally chose to preserve each router’s special arguments, only abstracting the most basic arguments, such as locations and profile (car, bike, pedestrian etc.), among others (full list here).

routingpy.routers.get_router_by_name(router_name)

Given a router’s name, try to return the router class.

>>> from routingpy.routers import get_router_by_name
>>> router = get_router_by_name("ors")(api_key='')
>>> print(router)
routingpy.routers.openrouteservice.ORS
>>> route = router.directions(**params)

If the string given is not recognized, a routingpy.exceptions.RouterNotFound exception is raised and the available list of router names is printed.

Parameters:

router_name (str) – Name of the router as string.

Return type:

Union[routingpy.routers.google.Google, routingpy.routers.graphhopper.Graphhopper, routingpy.routers.ign.IGN, routingpy.routers.mapbox_osrm.MapBoxOSRM, routingpy.routers.openrouteservice.ORS, routingpy.routers.osrm.OSRM, routingpy.routers.otp_v2.OpenTripPlannerV2, routingpy.routers.valhalla.Valhalla]

Default Options Object

class routingpy.routers.options

Contains default configuration options for all routers, e.g. timeout and proxies. Each router can take the same configuration values, which will override the values set in options object.

Example for overriding default values for user_agent and proxies:

>>> from routingpy.routers import options
>>> from routingpy.routers import MapboxOSRM
>>> options.default_user_agent = 'amazing_routing_app'
>>> options.default_proxies = {'https': '129.125.12.0'}
>>> router = MapboxOSRM(my_key)
>>> print(router.client.headers)
{'User-Agent': 'amazing_routing_app', 'Content-Type': 'application/x-www-form-urlencoded'}
>>> print(router.client.proxies)
{'https': '129.125.12.0'}
Attributes:
self.default_timeout:

Combined connect and read timeout for HTTP requests, in seconds. Specify “None” for no timeout. Integer.

self.default_retry_timeout:

Timeout across multiple retriable requests, in seconds. Integer.

self.default_retry_over_query_limit:

If True, client will not raise an exception on HTTP 429, but instead jitter a sleeping timer to pause between requests until HTTP 200 or retry_timeout is reached. Boolean.

self.default_skip_api_error:

Continue with batch processing if a routingpy.exceptions.RouterApiError is encountered (e.g. no route found). If False, processing will discontinue and raise an error. Boolean.

self.default_user_agent:

User-Agent to send with the requests to routing API. String.

self.default_proxies:

Proxies passed to the requests library. Dictionary.

default_proxies = None
default_retry_over_query_limit = True
default_retry_timeout = 60
default_skip_api_error = False
default_timeout = 60
default_user_agent = 'routingpy/v1.3.0'

Google

class routingpy.routers.Google(api_key: str, user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit=True, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the Google API services.

__init__(api_key: str, user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit=True, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Initializes a Google client.

Parameters:
  • api_key (str) – API key.

  • user_agent (str) – User Agent to be used when requesting. Default routingpy.routers.options.default_user_agent.

  • timeout (int or None) – Combined connect and read timeout for HTTP requests, in seconds. Specify None for no timeout. Default routingpy.routers.options.default_timeout.

  • retry_timeout (int) – Timeout across multiple retriable requests, in seconds. Default routingpy.routers.options.default_retry_timeout.

  • retry_over_query_limit (bool) – If True, client will not raise an exception on HTTP 429, but instead jitter a sleeping timer to pause between requests until HTTP 200 or retry_timeout is reached. Default routingpy.routers.options.default_over_query_limit.

  • skip_api_error (bool) – Continue with batch processing if a routingpy.exceptions.RouterApiError is encountered (e.g. no route found). If False, processing will discontinue and raise an error. Default routingpy.routers.options.default_skip_api_error.

  • client (abc.ABCMeta) – A client class for request handling. Needs to be derived from routingpy.client_base.BaseClient

  • client_kwargs (dict) – Additional arguments passed to the client, such as headers or proxies.

class WayPoint(position, waypoint_type='coords', stopover=True)

TODO: make the WayPoint class and its parameters appear in Sphinx. True for Valhalla as well.

Optionally construct a waypoint from this class with additional attributes.

Example:

>>> waypoint = Google.WayPoint(position=[8.15315, 52.53151], waypoint_type='coords', stopover=False)
>>> route = Google(api_key).directions(locations=[[[8.58232, 51.57234]], waypoint, [7.15315, 53.632415]])
directions(locations: List[List[float]], profile: str, alternatives: bool | None = None, avoid: List[str] | None = None, optimize: bool | None = None, language: str | None = None, region: str | None = None, units: str | None = None, arrival_time: int | None = None, departure_time: int | None = None, traffic_model: str | None = None, transit_mode: List[str] | Tuple[str] | None = None, transit_routing_preference: str | None = None, dry_run: bool | None = None)

Get directions between an origin point and a destination point.

For more information, visit https://developers.google.com/maps/documentation/directions/overview.

Parameters:
  • locations (list of list or list of Google.WayPoint) – The coordinates tuple the route should be calculated from in order of visit. Can be a list/tuple of [lon, lat], a list/tuple of address strings, Google’s Place ID’s, a Google.WayPoint instance or a combination of these. Note, the first and last location have to be specified as [lon, lat]. Optionally, specify optimize=true for via waypoint optimization.

  • profile (str) – The vehicle for which the route should be calculated. Default “driving”. One of [‘driving’, ‘walking’, ‘bicycling’, ‘transit’].

  • alternatives (bool) – Specifies whether more than one route should be returned. Only available for requests without intermediate waypoints. Default False.

  • avoid (list of str) – Indicates that the calculated route(s) should avoid the indicated features. One or more of [‘tolls’, ‘highways’, ‘ferries’, ‘indoor’]. Default None.

  • optimize (bool) – Optimize the given order of via waypoints (i.e. between first and last location). Default False.

  • language (str) – Language for routing instructions. The locale of the resulting turn instructions. Visit https://developers.google.com/maps/faq#languagesupport for options.

  • region (str) – Specifies the region code, specified as a ccTLD (“top-level domain”) two-character value. See https://developers.google.com/maps/documentation/directions/get-directions#RegionBiasing.

  • units (str) – Specifies the unit system to use when displaying results. One of [‘metric’, ‘imperial’].

  • arrival_time (int) – Specifies the desired time of arrival for transit directions, in seconds since midnight, January 1, 1970 UTC. Incompatible with departure_time.

  • departure_time – Specifies the desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC.

  • traffic_model (str) – Specifies the assumptions to use when calculating time in traffic. One of [‘best_guess’, ‘pessimistic’, ‘optimistic’. See https://developers.google.com/maps/documentation/directions/get-directions#optional-parameters for details.

  • transit_mode (list/tuple of str) – Specifies one or more preferred modes of transit. One or more of [‘bus’, ‘subway’, ‘train’, ‘tram’, ‘rail’].

  • transit_routing_preference (str) – Specifies preferences for transit routes. Using this parameter, you can bias the options returned, rather than accepting the default best route chosen by the API. One of [‘less_walking’, ‘fewer_transfers’].

  • dry_run (bool) – Print URL and parameters without sending the request.

Returns:

One or multiple route(s) from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction or routingpy.direction.Directions

matrix(locations: List[List[float]], profile: str, sources: List[int] | Tuple[int] | None = None, destinations: List[int] | Tuple[int] | None = None, avoid: List[str] | None = None, language: str | None = None, region: str | None = None, units: str | None = None, arrival_time: int | None = None, departure_time: int | None = None, traffic_model: str | None = None, transit_mode: List[str] | Tuple[str] | None = None, transit_routing_preference: str | None = None, dry_run: bool | None = None)

Gets travel distance and time for a matrix of origins and destinations.

Parameters:
  • locations (list of list) – Two or more pairs of lng/lat values.

  • profile (str) – The vehicle for which the route should be calculated. Default “driving”. One of [‘driving’, ‘walking’, ‘bicycling’, ‘transit’].

  • sources (list or tuple) – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • destinations (list or tuple) – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • avoid – Indicates that the calculated route(s) should avoid the indicated features. One or more of [‘tolls’, ‘highways’, ‘ferries’, ‘indoor’]. Default None.

  • avoid – list of str

  • language (str) – Language for routing instructions. The locale of the resulting turn instructions. Visit https://developers.google.com/maps/faq#languagesupport for options.

  • region (str) – Specifies the region code, specified as a ccTLD (“top-level domain”) two-character value. See https://developers.google.com/maps/documentation/directions/get-directions#RegionBiasing.

  • units (str) – Specifies the unit system to use when displaying results. One of [‘metric’, ‘imperial’].

  • arrival_time (int) – Specifies the desired time of arrival for transit directions, in seconds since midnight, January 1, 1970 UTC. Incompatible with departure_time.

  • departure_time (int) – Specifies the desired time of departure. You can specify the time as an integer in seconds since midnight, January 1, 1970 UTC.

  • traffic_model (str) – Specifies the assumptions to use when calculating time in traffic. One of [‘best_guess’, ‘pessimistic’, ‘optimistic’. See https://developers.google.com/maps/documentation/directions/get-directions#optional-parameters for details.

  • transit_mode (list of str or tuple of str) – Specifies one or more preferred modes of transit. One or more of [‘bus’, ‘subway’, ‘train’, ‘tram’, ‘rail’].

  • transit_routing_preference (str) – Specifies preferences for transit routes. Using this parameter, you can bias the options returned, rather than accepting the default best route chosen by the API. One of [‘less_walking’, ‘fewer_transfers’].

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

A matrix from the specified sources and destinations.

Return type:

routingpy.matrix.Matrix

Graphhopper

class routingpy.routers.Graphhopper(api_key: str | None = None, base_url: str | None = 'https://graphhopper.com/api/1', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the Graphhopper API services.

__init__(api_key: str | None = None, base_url: str | None = 'https://graphhopper.com/api/1', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Initializes an graphhopper client.

Parameters:
directions(locations: List[List[float]] | Tuple[Tuple[float]], profile: str, format: str | None = None, optimize: bool | None = None, instructions: bool | None = None, locale: str | None = None, elevation: bool | None = None, points_encoded: bool | None = True, calc_points: bool | None = None, debug: bool | None = None, point_hints: List[str] | None = None, details: List[str] | None = None, ch_disable: bool | None = None, custom_model: dict | None = None, headings: List[int] | None = None, heading_penalty: int | None = None, pass_through: bool | None = None, algorithm: str | None = None, round_trip_distance: int | None = None, round_trip_seed: int | None = None, alternative_route_max_paths: int | None = None, alternative_route_max_weight_factor: float | None = None, alternative_route_max_share_factor: float | None = None, dry_run: bool | None = None, snap_preventions: List[str] | None = None, curbsides: List[str] | None = None, **direction_kwargs)

Get directions between an origin point and a destination point.

Use direction_kwargs for any missing directions request options.

For more information, visit https://docs.graphhopper.com/openapi/routing/postroute.

Parameters:
  • locations (list of list or tuple of tuple) – The coordinates tuple the route should be calculated from in order of visit.

  • profile (str) – The vehicle for which the route should be calculated. One of [“car” “bike” “foot” “hike” “mtb” “racingbike” “scooter” “truck” “small_truck”]. Default “car”.

  • format (str) – Specifies the resulting format of the route, for json the content type will be application/json. Default “json”.

  • locale (str) – Language for routing instructions. The locale of the resulting turn instructions. E.g. pt_PT for Portuguese or de for German. Default “en”.

  • optimize (bool) – If false the order of the locations will be identical to the order of the point parameters. If you have more than 2 points you can set this optimize parameter to True and the points will be sorted regarding the minimum overall time - e.g. suiteable for sightseeing tours or salesman. Keep in mind that the location limit of the Route Optimization API applies and the credit costs are higher! Note to all customers with a self-hosted license: this parameter is only available if your package includes the Route Optimization API. Default False.

  • instructions (bool) – Specifies whether to return turn-by-turn instructions. Default True.

  • elevation (bool) – If true a third dimension - the elevation - is included in the polyline or in the GeoJson. IMPORTANT: If enabled you have to use a modified version of the decoding method or set points_encoded to false. See the points_encoded attribute for more details. Additionally a request can fail if the vehicle does not support elevation. See the features object for every vehicle. Default False.

  • points_encoded (bool) – If False the coordinates in point and snapped_waypoints are returned as array using the order [lon,lat,elevation] for every point. If true the coordinates will be encoded as string leading to less bandwith usage. Default True.

  • calc_points (bool) – If the points for the route should be calculated at all, printing out only distance and time. Default True.

  • debug (bool) – If True, the output will be formated. Default False.

  • point_hints (list of str) – The point_hints is typically a road name to which the associated point parameter should be snapped to. Specify no point_hint parameter or the same number as you have locations. Optional.

  • details (list of str) – Optional parameter to retrieve path details. You can request additional details for the route: street_name, time, distance, max_speed, toll, road_class, road_class_link, road_access, road_environment, lanes, and surface.

  • ch_disable (bool) – Always use ch_disable=true in combination with one or more parameters of this table. Default False.

  • custom_model (dict) – The custom_model modifies the routing behaviour of the specified profile. See https://docs.graphhopper.com/openapi/custom-model

  • headings (list of int) – Optional parameter. Favour a heading direction for a certain point. Specify either one heading for the start point or as many as there are points. In this case headings are associated by their order to the specific points. Headings are given as north based clockwise angle between 0 and 360 degree.

  • heading_penalty (int) – Optional parameter. Penalty for omitting a specified heading. The penalty corresponds to the accepted time delay in seconds in comparison to the route without a heading. Default 120.

  • pass_through (bool) – Optional parameter. If true u-turns are avoided at via-points with regard to the heading_penalty. Default False.

  • algorithm (str) – Optional parameter. round_trip or alternative_route.

  • round_trip_distance (int) – If algorithm=round_trip this parameter configures approximative length of the resulting round trip. Default 10000.

  • round_trip_seed (int) – If algorithm=round_trip this parameter introduces randomness if e.g. the first try wasn’t good. Default 0.

  • alternative_route_max_paths (int) – If algorithm=alternative_route this parameter sets the number of maximum paths which should be calculated. Increasing can lead to worse alternatives. Default 2.

  • alternative_route_max_weight_factor (float) – If algorithm=alternative_route this parameter sets the factor by which the alternatives routes can be longer than the optimal route. Increasing can lead to worse alternatives. Default 1.4.

  • alternative_route_max_share_factor (float) – If algorithm=alternative_route this parameter specifies how much alternatives routes can have maximum in common with the optimal route. Increasing can lead to worse alternatives. Default 0.6.

  • dry_run (bool) – Print URL and parameters without sending the request.

  • snap_preventions (list of str) – Optional parameter to avoid snapping to a certain road class or road environment. Currently supported values are motorway, trunk, ferry, tunnel, bridge and ford. Optional.

  • curbsides (list of str) – One of “any”, “right”, “left”. It specifies on which side a point should be relative to the driver when she leaves/arrives at a start/target/via point. You need to specify this parameter for either none or all points. Only supported for motor vehicles and OpenStreetMap.

Returns:

One or multiple route(s) from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction or routingpy.direction.Directions

Changed in version 0.3.0: point_hint used to be bool, which was not the right usage.

Added in version 0.3.0: snap_prevention, curb_side, turn_costs parameters

Changed in version 1.2.0: Renamed point_hint to point_hints, heading to headings, snap_prevention to snap_preventions, curb_side to curbsides,

Added in version 1.2.0: Added custom_model parameter

Deprecated since version 1.2.0: Removed weighting, block_area, avoid, turn_costs parameters

isochrones(locations: Tuple[float] | List[float], profile: str, intervals: List[int] | Tuple[int], type: str | None = 'json', buckets: int | None = 1, interval_type: str | None = 'time', reverse_flow: bool | None = None, debug: bool | None = None, dry_run: bool | None = None, **isochrones_kwargs)

Gets isochrones or equidistants for a range of time/distance values around a given set of coordinates.

Use isochrones_kwargs for missing isochrones request options.

For more details visit https://docs.graphhopper.com/openapi/isochrones.

Parameters:
  • locations (tuple of float or list of float) – One coordinate pair denoting the location.

  • profile (str) – Specifies the mode of transport. One of “car” “bike” “foot” “hike” “mtb” “racingbike” “scooter” “truck” “small_truck”. Default “car”.

  • intervals (list of int or tuple of int) – Maximum range to calculate distances/durations for. You can also specify the buckets variable to break the single value into more isochrones. For compatibility reasons, this parameter is expressed as list. In meters or seconds depending on interval_type.

  • interval_type (str) – Set time for isochrones or distance for equidistants. Default ‘time’.

  • buckets (int) – For how many sub intervals an additional polygon should be calculated. Default 1.

  • reverse_flow – If false the flow goes from point to the polygon, if true the flow goes from the polygon “inside” to the point. Default False.

  • reverse_flow – bool

  • debug (bool) – If true, the output will be formatted. Default False

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

An isochrone with the specified range.

Return type:

routingpy.isochrone.Isochrones

matrix(locations: List[List[float] | Tuple[float]] | Tuple[List[float] | Tuple[float]], profile: str, sources: List[int] | None = None, destinations: List[int] | None = None, out_array: List[str] | None = ['times', 'distances'], debug=None, dry_run: bool | None = None, **matrix_kwargs)

Gets travel distance and time for a matrix of origins and destinations.

Use matrix_kwargs for any missing matrix request options.

For more details visit https://docs.graphhopper.com/openapi/matrices.

Parameters:
  • locations (List[List[float]|Tuple[float]]|Tuple[List[float]|Tuple[float]]) – Specify multiple points for which the weight-, route-, time- or distance-matrix should be calculated. In this case the starts are identical to the destinations. If there are N points, then NxN entries will be calculated. The order of the point parameter is important. Specify at least three points. Is a string with the format latitude,longitude.

  • profile (str) – Specifies the mode of transport. One of bike, car, foot or other vehicles supported by GraphHopper (see https://docs.graphhopper.com/openapi/map-data-and-routing-profiles). Default “car”.

  • sources (List[int]) – The starting points for the routes. Specifies an index referring to locations.

  • destinations (List[int]) – The destination points for the routes. Specifies an index referring to locations.

  • out_array (List[str]) – Specifies which arrays should be included in the response. Specify one or more of the following options ‘weights’, ‘times’, ‘distances’. The units of the entries of distances are meters, of times are seconds and of weights is arbitrary and it can differ for different vehicles or versions of this API. Default [“times”, “distance”].

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

A matrix from the specified sources and destinations.

Return type:

routingpy.matrix.Matrix

IGN

class routingpy.routers.IGN(base_url: str | None = 'https://data.geopf.fr/navigation', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the IGN Geoportail “itineraire” geoservices

__init__(base_url: str | None = 'https://data.geopf.fr/navigation', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Initializes an IGN client.

Parameters:
directions(locations: List[List[float]] = [], profile: str | None = 'car', resource: str = 'bdtopo-osrm', optimization: str | None = None, geometry_format: str | None = None, constraints: str | dict | List[str] | None = None, getSteps: bool | None = None, getBbox: bool | None = None, crs: str | None = None, waysAttributes: List[str] | None = None, dry_run: bool | None = None, **direction_kwargs)

Get directions between an origin point and a destination point.

For more information, visit https://www.geoportail.gouv.fr/depot/swagger/itineraire.html

Use direction_kwargs for any missing directions request options.

Parameters:
  • locations – The coordinates tuple the route should be calculated from in order of visit.

  • profile – Optionally specifies the mode of transport to use when calculating directions. Should be “car” (default) or “pedestrian”; resource “bdtopo-osrm” also supports “exceptionnal”.

  • resource – The routing resource to use. Should be one of “bdtopo-osrm”, “bdtopo-pgr”, “bdtopo-valhalla”

  • optimization – Optimization mode used to compute the route “fastest” (default) or “shortest”.

  • geometry_format – Format of returned geometries. One of “geojson” (default) or “polyline”

  • constraints – Route constraints. May be a JSON-serializable object or a pre-serialized string.

  • getSteps – Include step-by-step instructions. Defaults to “true”.

  • getBbox – Include route bounding box in the response. Defaults to “true”.

  • crs – Coordinate reference system for returned geometries. Default is “EPSG:4326” (WGS84 : latitude/longitude), other options depend on resource used.

  • dry_run – Print URL and parameters without sending the request.

  • direction_kwargs – any additional keyword arguments which will override parameters

Returns:

A route from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction

static get_direction_params(locations: List[List[float]], profile: str | None = 'car', resource: str = 'bdtopo-osrm', optimization: str | None = None, geometry_format: str | None = None, constraints: str | dict | List[str] | None = None, getSteps: bool | None = None, getBbox: bool | None = None, crs: str | None = None, waysAttributes: List[str] | None = None, **direction_kwargs)

Builds and returns the router’s route parameters. It’s a separate function so that bindings can use routingpy’s functionality. See documentation of .directions().

isochrones(locations: List[float], intervals: List[int] | Tuple[int] | int, interval_type: str | None = 'time', profile: str | None = 'car', resource: str | None = 'bdtopo-valhalla', direction: str | None = None, constraints: str | dict | List[str] | None = None, geometry_format: str | None = None, crs: str | None = None, dry_run: bool | None = None)

Get isochrone (or equidistant) around a location using the IGN Geoportail isochrone service, see https://www.geoportail.gouv.fr/depot/swagger/itineraire.html#/Utilisation/isochrone

This method calls the IGN “isochrone” operation of the itineraire API and returns polygonal contour for the requested interval. Consult the service’s GetCapabilities for valid values for resource, profile, and other provider-specific options.

Parameters:
  • locations ([float, float]) – One pair of lng/lat values, expressed in the resource CRS.

  • intervals (int) – Integer range for which to compute isochrone/equidistant. Value represents seconds when interval_type is “time”, or meters when interval_type is “distance”. Note that only one contour can be calculated by the API. For compatibility reasons, it is possible to pass this value in a list or tuple, or as a single integer. If multiple values are passed, only the first one will be used.

  • interval_type (str) – Type of the provided ranges: “time” for isochrones (default) or “distance” for equidistants.

  • profile (str) – see distance method for details. Default “car”.

  • resource – one of “bdtopo-valhalla” (default), “bdtopo-pgr”. Note: “bdtopo-osrm” does not support isochrones.

  • direction (str) – Directionality of the calculation. Should be “departure” (defaults, gives potential arrival points) or “arrival” (gives potential starting points).

  • constraints – see distance method documentation.

  • geometry_format – see distance method documentation.

  • crs – see distance method documentation.

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

An isochrone with the specified range.

Return type:

routingpy.isochrone.Isochrones

Raises:

ValueError – If required parameters are missing or malformed (for example, if locations is not a valid coordinate pair or if intervals is empty).

MapboxOSRM

class routingpy.routers.MapboxOSRM(api_key: str, user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the OSRM API services.

__init__(api_key: str, user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Initializes a Mapbox OSRM client.

Parameters:
directions(locations: List[List[float]], profile: str, radiuses: List[float] | Tuple[float] | None = None, bearings: List[List[int]] | None = None, alternatives: bool | None = None, steps: bool | None = None, continue_straight: bool | None = None, annotations: List[str] | None = None, geometries: str | None = None, overview: str | None = None, exclude: str | None = None, approaches: List[str] | None = None, banner_instructions: bool | None = None, language: str | None = None, roundabout_exits: bool | None = None, voice_instructions: bool | None = None, voice_units: str | None = None, waypoint_names: List[str] | None = None, waypoint_targets: List[List[float]] | None = None, dry_run: bool | None = None)

Get directions between an origin point and a destination point.

For more information, visit https://docs.mapbox.com/api/navigation/directions/.

Parameters:
  • locations (list of list) – The coordinates tuple the route should be calculated from in order of visit.

  • profile (str) – Specifies the mode of transport to use when calculating directions. One of [“driving-traffic”, “driving”, “walking”, “cycling”].

  • radiuses (list or tuple) – A list of maximum distances (measured in meters) that limit the search of nearby road segments to every given waypoint. The values must be greater than 0, an empty element signifies to use the backend default radius. The number of radiuses must correspond to the number of waypoints.

  • bearings (list of list of int) – Specifies a list of pairs (bearings and deviations) to filter the segments of the road network a waypoint can snap to. For example bearings=[[45,10],[120,20]]. Each pair is a comma-separated list that can consist of one or two float values, where the first value is the bearing and the second one is the allowed deviation from the bearing. The bearing can take values between 0 and 360 clockwise from true north. If the deviation is not set, then the default value of 100 degrees is used. The number of pairs must correspond to the number of waypoints.

  • alternatives (bool) – Search for alternative routes and return as well. A result cannot be guaranteed. Default false.

  • steps (bool) – Return route steps for each route leg. Default false.

  • continue_straight (bool) – Forces the route to keep going straight at waypoints constraining uturns there even if it would be faster. Default value depends on the profile.

  • annotations (list of str) – Returns additional metadata for each coordinate along the route geometry. One of [duration, distance, speed, congestion].

  • geometries (str) – Returned route geometry format (influences overview and per step). One of [“polyline”, “polyline6”, “geojson”. Default polyline.

  • overview (str) – Add overview geometry either full, simplified according to highest zoom level it could be display on, or not at all. One of [“simplified”, “full”, “false”, False]. Default simplified.

  • exclude (str) – Exclude certain road types from routing. One of [‘toll’, ‘motorway’, ‘ferry’] if profile=driving*. ‘ferry’ for profile=cycling. None for profile=walking. Default none.

  • approaches (list of str) – Indicating the side of the road from which to approach waypoint in a requested route. One of [“unrestricted”, “curb”]. unrestricted: route can arrive at the waypoint from either side of the road. curb: route will arrive at the waypoint on the driving_side of the region. If provided, the number of approaches must be the same as the number of waypoints. Default unrestricted.

  • banner_instructions (bool) – Whether to return banner objects associated with the route steps. Default False.

  • language (str) – The language of returned turn-by-turn text instructions. Default is en. See the full list here of supported languages here: https://docs.mapbox.com/api/navigation/directions/#instructions-languages

  • roundabout_exits (bool) – Whether to emit instructions at roundabout exits or not. Without this parameter, roundabout maneuvers are given as a single instruction that includes both entering and exiting the roundabout. With roundabout_exits=true, this maneuver becomes two instructions, one for entering the roundabout and one for exiting it. Default false.

  • voice_instructions (bool) – Whether to return SSML marked-up text for voice guidance along the route or not. Default false.

  • voice_units (str) – Specify which type of units to return in the text for voice instructions. One of [“imperial”, “metric”]. Default imperial.

  • waypoint_names (list of str) – List of custom names for entries in the list of coordinates, used for the arrival instruction in banners and voice instructions. Values can be any string, and the total number of all characters cannot exceed 500. If provided, the list of waypoint_names must be the same length as the list of coordinates. The first value in the list corresponds to the route origin, not the first destination.

  • waypoint_targets (list of list of float) – List of coordinate pairs used to specify drop-off locations that are distinct from the locations specified in coordinates. If this parameter is provided, the Directions API will compute the side of the street, left or right, for each target based on the waypoint_targets and the driving direction. The maneuver.modifier, banner and voice instructions will be updated with the computed side of street. The number of waypoint_targets must be the same as the number of coordinates.

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

One or multiple route(s) from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction or routingpy.direction.Directions

isochrones(locations: List[float], profile: str, intervals: List[int], contours_colors: List[str] | None = None, polygons: bool | None = None, denoise: float | None = None, generalize: float | None = None, dry_run: bool | None = None)

Gets isochrones or equidistants for a range of time values around a given set of coordinates.

For more information, visit https://docs.mapbox.com/api/navigation/isochrone/.

Parameters:
  • locations (list of float) – One pair of lng/lat values. Takes the form [Longitude, Latitude].

  • profile (str) – Specifies the mode of transport to use when calculating directions. One of [“driving”, “walking”, “cycling”.

  • intervals (list of int) – Time ranges to calculate isochrones for. Up to 4 ranges are possible. In seconds.

  • contours_colors (list of str) – The color for the output of the contour. Specify it as a Hex value, but without the #, such as “color”:”ff0000” for red. If no color is specified, the isochrone service will assign a default color to the output.

  • polygons (bool) – Controls whether polygons or linestrings are returned in GeoJSON geometry. Default False.

  • denoise (float) – Can be used to remove smaller contours. In range [0, 1]. A value of 1 will only return the largest contour for a given time value. A value of 0.5 drops any contours that are less than half the area of the largest contour in the set of contours for that same time value. Default 1.

  • generalize (float) – A floating point value in meters used as the tolerance for Douglas-Peucker generalization. Note: Generalization of contours can lead to self-intersections, as well as intersections of adjacent contours.

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

An isochrone with the specified range.

Return type:

routingpy.isochrone.Isochrones

matrix(locations: List[float] | Tuple[float], profile: str, sources: List[int] | Tuple[int] | None = None, destinations: List[int] | Tuple[int] | None = None, annotations: List[str] | None = None, fallback_speed: int | None = None, dry_run: bool | None = None)

Gets travel distance and time for a matrix of origins and destinations.

For more information visit https://docs.mapbox.com/api/navigation/matrix/.

Parameters:
  • locations (list or tuple) – The coordinates tuple the route should be calculated from in order of visit.

  • profile (str) – Specifies the mode of transport to use when calculating directions. One of [“car”, “bike”, “foot”].

  • sources (list or tuple) – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • destinations (list or tuple) – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • annotations (list of str) – Used to specify the resulting matrices. One or more of [“duration”, “distance”]. Default [“duration”]

  • fallback_speed (int) – By default, if there is no possible route between two points, the Matrix API sets the resulting matrix element to null. To circumvent this behavior, set the fallback_speed parameter to a value greater than 0 in kilometers per hour. The Matrix API will replace a null value with a straight-line estimate between the source and destination based on the provided speed value.

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

A matrix from the specified sources and destinations.

Return type:

routingpy.matrix.Matrix

OpenTripPlannerV2

class routingpy.routers.OpenTripPlannerV2(base_url: str | None = 'http://localhost:8080', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Bases: object

Performs requests over OpenTripPlannerV2 GraphQL API.

__init__(base_url: str | None = 'http://localhost:8080', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Initializes an OpenTripPlannerV2 client.

Parameters:
directions(locations: List[List[float]], profile: str | None = 'WALK,TRANSIT', date: date | None = datetime.date(2026, 2, 12), time: time | None = datetime.time(14, 33, 43, 758379), arrive_by: bool | None = False, num_itineraries: int | None = 3, dry_run: bool | None = None)

Get directions between an origin point and a destination point.

Parameters:
  • locations (list of list of float) – List of coordinates for departure and arrival points as [[lon,lat], [lon,lat]].

  • profile (str) – Comma-separated list of transportation modes that the user is willing to use. Default: “WALK,TRANSIT”

  • date (datetime.date) – Date of departure or arrival. Default value: current date.

  • time (datetime.time) – Time of departure or arrival. Default value: current time.

  • num_itineraries (int) – The maximum number of itineraries to return. Default value: 3.

  • dry_run (bool) – Print URL and parameters without sending the request.

Arrive_by:

Whether the itinerary should depart at the specified time (False), or arrive to the destination at the specified time (True). Default value: False.

Returns:

One or multiple route(s) from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction or routingpy.direction.Directions

isochrones(locations: List[float], profile: str | None = 'WALK,TRANSIT', time: datetime | None = datetime.datetime(2026, 2, 12, 14, 33, 43, 758419, tzinfo=datetime.timezone.utc), cutoffs: List[int] | None = [3600], arrive_by: bool | None = False, dry_run: bool | None = None)

Gets isochrones for a range of time values around a given set of coordinates.

Parameters:
  • locations (list of float) – Origin of the search as [lon,lat].

  • profile (str) – Comma-separated list of transportation modes that the user is willing to use. Default: “WALK,TRANSIT”

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Time:

Departure date and time (timezone aware). The default value is now (UTC).

Cutoff:

The maximum travel duration in seconds. The default value is one hour.

Arrive_by:

Set to False when searching from the location and True when searching to the location. Default value: False.

Returns:

An isochrone with the specified range.

Return type:

routingpy.isochrone.Isochrones

raster(locations: List[float], profile: str | None = 'WALK,TRANSIT', time: datetime | None = datetime.datetime(2026, 2, 12, 14, 33, 43, 758439), cutoff: int | None = 3600, arrive_by: bool | None = False, dry_run: bool | None = None)

Get raster for a time value around a given set of coordinates.

Parameters:
  • locations (list of float) – Origin of the search as [lon,lat].

  • profile (str) – Comma-separated list of transportation modes that the user is willing to use. Default: “WALK,TRANSIT”

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Time:

Departure date and time (timezone aware). The default value is now (UTC).

Cutoff:

The maximum travel duration in seconds. The default value is one hour.

Arrive_by:

Set to False when searching from the location and True when searching to the location. Default value: False.

Returns:

A raster with the specified range.

Return type:

routingpy.raster.Raster

ORS

class routingpy.routers.ORS(api_key: str | None = None, base_url: str | None = 'https://api.openrouteservice.org', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the ORS API services.

__init__(api_key: str | None = None, base_url: str | None = 'https://api.openrouteservice.org', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Initializes an openrouteservice client.

Parameters:
directions(locations: List[List[float]], profile: str, format: str | None = 'geojson', preference: str | None = None, alternative_routes: dict | None = None, language: str | None = None, geometry: bool | None = None, geometry_simplify: bool | None = None, instructions: bool | None = None, instructions_format: str | None = None, roundabout_exits: bool | None = None, attributes: List[str] | None = None, radiuses: List[int] | None = None, maneuvers: bool | None = None, bearings: List[List[float]] | None = None, continue_straight: bool | None = None, elevation: bool | None = None, extra_info: List[str] | None = None, suppress_warnings: bool | None = None, options: dict | None = None, dry_run: bool | None = None)

Get directions between an origin point and a destination point.

For more information, visit https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/post

Parameters:
  • locations (list of list) – The coordinates tuple the route should be calculated from in order of visit.

  • profile (str) – Specifies the mode of transport to use when calculating directions. One of [“driving-car”, “driving-hgv”, “foot-walking”, “foot-hiking”, “cycling-regular”, “cycling-road”, “cycling-mountain”, “cycling-electric”,]. Default “driving-car”.

  • format (str) – Specifies the response format. One of [‘json’, ‘geojson’]. Default “json”. Geometry format for “json” is Google’s encodedpolyline.

  • preference (str) – Specifies the routing preference. One of [“fastest, “shortest”, “recommended”]. Default fastest.

  • alternative_routes (dict) – Specifies whether alternative routes are computed, and parameters for the algorithm determining suitable alternatives. Must contain “share_factor”, “target_count” and “weight_factor”.

  • language (str) – Language for routing instructions. One of [“en”, “de”, “cn”, “es”, “ru”, “dk”, “fr”, “it”, “nl”, “br”, “se”, “tr”, “gr”].

  • geometry (bool) – Specifies whether geometry should be returned. Default True.

  • geometry_simplify (bool) – Specifies whether to simplify the geometry. Default False.

  • instructions (bool) – Specifies whether to return turn-by-turn instructions. Default True.

  • instructions_format (str) – Specifies the the output format for instructions. One of [“text”, “html”]. Default “text”.

  • roundabout_exits (bool) – Provides bearings of the entrance and all passed roundabout exits. Adds the ‘exit_bearings’ array to the ‘step’ object in the response. Default False.

  • attributes (list of str) – Returns route attributes on [“avgspeed”, “detourfactor”, “percentage”]. Must be a list of strings. Default None.

  • maneuvers (bool) – Specifies whether the maneuver object is included into the step object or not. Default: False.

  • radiuses (list of int) – A list of maximum distances (measured in meters) that limit the search of nearby road segments to every given waypoint. The values must be greater than 0, the value of -1 specifies no limit in the search. The number of radiuses must correspond to the number of waypoints. Default 50 km (ORS backend).

  • bearings (list of list) – Specifies a list of pairs (bearings and deviations) to filter the segments of the road network a waypoint can snap to. For example bearings=[[45,10],[120,20]]. Each pair is a comma-separated list that can consist of one or two float values, where the first value is the bearing and the second one is the allowed deviation from the bearing. The bearing can take values between 0 and 360 clockwise from true north. If the deviation is not set, then the default value of 100 degrees is used. The number of pairs must correspond to the number of waypoints. Setting optimized=false is mandatory for this feature to work for all profiles. The number of bearings corresponds to the length of waypoints-1 or waypoints. If the bearing information for the last waypoint is given, then this will control the sector from which the destination waypoint may be reached.

  • continue_straight (bool) – Forces the route to keep going straight at waypoints not restricting U-turns even if U-turns would be faster. Default False.

  • elevation (bool) – Specifies whether to return elevation values for points. Default False.

  • extra_info (list of str) – Returns additional information on [“steepness”, “suitability”, “surface”, “waycategory”, “waytype”, “tollways”, “traildifficulty”, “roadaccessrestrictions”]. Must be a list of strings. Default None.

  • suppress_warnings (bool) – Tells the system to not return any warning messages in extra_info.

  • options (dict) – Refer to https://openrouteservice.org/dev/#/api-docs/v2/directions/{profile}/geojson/post for detailed documentation. Construct your own dict() options object and paste it to your code.

  • dry_run (bool) – Print URL and parameters without sending the request.

Returns:

A route from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction

isochrones(locations: List[float], profile: str, intervals: List[int], interval_type: str | None = 'time', location_type: str | None = 'start', smoothing: float | None = None, attributes: List[str] | None = None, intersections: bool | None = None, dry_run: bool | None = None)

Gets isochrones or equidistants for a range of time/distance values around a given set of coordinates.

Parameters:
  • locations (list of float) – One pair of lng/lat values.

  • profile (str) – Specifies the mode of transport to use when calculating directions. One of [“driving-car”, “driving-hgv”, “foot-walking”, “foot-hiking”, “cycling-regular”, “cycling-safe”, “cycling-mountain”, “cycling-electric”,]. Default “driving-car”.

  • interval_type (str) – Set ‘time’ for isochrones or ‘distance’ for equidistants. Default ‘time’.

  • intervals (list of int) – Ranges to calculate distances/durations for. This can be a list of multiple ranges, e.g. [600, 1200, 1400]. In meters or seconds.

  • location_type (str) – ‘start’ treats the location(s) as starting point, ‘destination’ as goal. Default ‘start’.

  • smoothing (float) – Applies a level of generalisation to the isochrone polygons generated. Value between 0 and 1, whereas a value closer to 1 will result in a more generalised shape.

  • attributes (list of str) – ‘area’ returns the area of each polygon in its feature properties. ‘reachfactor’ returns a reachability score between 0 and 1. ‘total_pop’ returns population statistics from https://ghsl.jrc.ec.europa.eu/about.php. One or more of [‘area’, ‘reachfactor’, ‘total_pop’]. Default ‘area’.

  • intersections (bool) – Specifies whether to return intersecting polygons.

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

An isochrone with the specified range.

Return type:

routingpy.isochrone.Isochrones

matrix(locations: List[List[float]], profile: str, sources: List[int] | None = None, destinations: List[int] | None = None, metrics: List[str] | None = None, resolve_locations: bool | None = None, dry_run: bool | None = None)

Gets travel distance and time for a matrix of origins and destinations.

Parameters:
  • locations (list of list) – Two or more pairs of lng/lat values.

  • profile (str) – Specifies the mode of transport to use when calculating directions. One of [“driving-car”, “driving-hgv”, “foot-walking”, “foot-hiking”, “cycling-regular”, “cycling-road”, “cycling-mountain”, “cycling-electric”,]. Default “driving-car”.

  • sources (list of int) – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • destinations (list of int) – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • metrics (list of str) – Specifies a list of returned metrics. One or more of [“distance”, “duration”]. Default [‘duration’].

  • resolve_locations (bool) – Specifies whether given locations are resolved or not. If set ‘true’, every element in destinations and sources will contain the name element that identifies the name of the closest street. Default False.

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

A matrix from the specified sources and destinations.

Return type:

routingpy.matrix.Matrix

OSRM

class routingpy.routers.OSRM(base_url: str | None = 'https://routing.openstreetmap.de/routed-bike', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the OSRM API services.

__init__(base_url: str | None = 'https://routing.openstreetmap.de/routed-bike', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Initializes an OSRM client.

Parameters:
directions(locations: List[List[float]], profile: str | None = 'driving', radiuses: List[int] | None = None, bearings: List[List[float]] | None = None, alternatives: bool | int | None = None, steps: bool | None = None, continue_straight: bool | None = None, annotations: bool | None = None, geometries: str | None = None, overview: str | None = None, dry_run: bool | None = None, **direction_kwargs)

Get directions between an origin point and a destination point.

Use direction_kwargs for any missing directions request options.

For more information, visit http://project-osrm.org/docs/v5.5.1/api/#route-service.

Parameters:
  • profile (str) – NOT USED, only for compatibility with other providers.

  • locations (list of list) – The coordinates tuple the route should be calculated from in order of visit.

  • profile – Optionally specifies the mode of transport to use when calculating directions. Note that this strongly depends on how the OSRM server works. E.g. the public FOSSGIS instances ignore any profile parameter set this way and instead chose to encode the ‘profile’ in the base URL, e.g. https://routing.openstreetmap.de/routed-bike. Default “driving”.

  • radiuses (list of int) – A list of maximum distances (measured in meters) that limit the search of nearby road segments to every given waypoint. The values must be greater than 0, an empty element signifies to use the backend default radius. The number of radiuses must correspond to the number of waypoints.

  • bearings (list of list) – Specifies a list of pairs (bearings and deviations) to filter the segments of the road network a waypoint can snap to. For example bearings=[[45,10],[120,20]]. Each pair is a comma-separated list that can consist of one or two float values, where the first value is the bearing and the second one is the allowed deviation from the bearing. The bearing can take values between 0 and 360 clockwise from true north. If the deviation is not set, then the default value of 100 degrees is used. The number of pairs must correspond to the number of waypoints.

  • alternatives (bool or int) – Search for alternative routes. A result cannot be guaranteed. Accepts an integer or False. Default False.

  • steps (bool) – Return route steps for each route leg. Default false.

  • continue_straight (bool) – Forces the route to keep going straight at waypoints constraining U-turns there even if it would be faster. Default value depends on the profile.

  • annotations (bool) – Returns additional metadata for each coordinate along the route geometry. Default false.

  • geometries (str) – Returned route geometry format (influences overview and per step). One of [“polyline”, “polyline6”, “geojson”. Default polyline.

  • overview (str) – Add overview geometry either full, simplified according to the highest zoom level it could be display on, or not at all. One of [“simplified”, “full”, “false”, False]. Default simplified.

  • dry_run – Print URL and parameters without sending the request.

  • dry_run – bool

Returns:

One or multiple route(s) from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction or routingpy.direction.Directions

static get_direction_params(locations, profile, radiuses=None, bearings=None, alternatives=None, steps=None, continue_straight=None, annotations=None, geometries=None, overview=None, **directions_kwargs)

Builds and returns the router’s route parameters. It’s a separate function so that bindings can use routingpy’s functionality. See documentation of .directions().

Parameters:
  • locations – NOT USED, only for consistency reasons with other providers.

  • profile – NOT USED, only for consistency reasons with other providers.

static get_matrix_params(locations, profile, radiuses=None, bearings=None, sources=None, destinations=None, annotations=('duration', 'distance'), **matrix_kwargs)

Builds and returns the router’s route parameters. It’s a separate function so that bindings can use routingpy’s functionality. See documentation of .matrix().

Parameters:
  • locations – NOT USED, only for consistency reasons with other providers.

  • profile – NOT USED, only for consistency reasons with other providers.

matrix(locations: List[List[float]], profile: str | None = 'driving', radiuses: List[int] | None = None, bearings: List[List[float]] | None = None, sources: List[int] | None = None, destinations: List[int] | None = None, dry_run: bool | None = None, annotations: List[str] | None = ('duration', 'distance'), **matrix_kwargs)

Gets travel distance and time for a matrix of origins and destinations.

Use matrix_kwargs for any missing matrix request options.

For more information visit http://project-osrm.org/docs/v5.5.1/api/#table-service.

Parameters:
  • locations (list of list) – The coordinates tuple the route should be calculated from.

  • profile (str) – Optionally specifies the mode of transport to use when calculating directions. Note that this strongly depends on how the OSRM server works. E.g. the public FOSSGIS instances ignore any profile parameter set this way and instead chose to encode the ‘profile’ in the base URL, e.g. https://routing.openstreetmap.de/routed-bike. Default “driving”.

  • radiuses (list of int) – A list of maximum distances (measured in meters) that limit the search of nearby road segments to every given waypoint. The values must be greater than 0, an empty element signifies to use the backend default radius. The number of radiuses must correspond to the number of waypoints.

  • bearings (list of list) – Specifies a list of pairs (bearings and deviations) to filter the segments of the road network a waypoint can snap to. For example bearings=[[45,10],[120,20]]. Each pair is a comma-separated list that can consist of one or two float values, where the first value is the bearing and the second one is the allowed deviation from the bearing. The bearing can take values between 0 and 360 clockwise from true north. If the deviation is not set, then the default value of 100 degrees is used. The number of pairs must correspond to the number of waypoints.

  • sources (list of int) – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • destinations (list of int) – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • dry_run (bool) – Print URL and parameters without sending the request.

  • annotations (List[str]) – Return the requested table or tables in response. One or more of [“duration”, “distance”].

Returns:

A matrix from the specified sources and destinations.

Return type:

routingpy.matrix.Matrix

Changed in version 0.3.0: Add annotations parameter to get both distance and duration

Valhalla

class routingpy.routers.Valhalla(base_url: str = 'https://valhalla1.openstreetmap.de', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs: dict)

Performs requests to a Valhalla instance.

__init__(base_url: str = 'https://valhalla1.openstreetmap.de', user_agent: str | None = None, timeout: int | None = DEFAULT, retry_timeout: int | None = None, retry_over_query_limit: bool | None = False, skip_api_error: bool | None = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs: dict)

Initializes a Valhalla client.

Parameters:
class Waypoint(position, **kwargs)

Constructs a waypoint with additional information or constraints.

Refer to Valhalla’s documentation for details: https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#locations

Use kwargs to specify options, make sure the value is proper for each option.

Example:

>>> waypoint = Valhalla.WayPoint(position=[8.15315, 52.53151], type='through', heading=120, heading_tolerance=10, minimum_reachability=10, radius=400)
>>> route = Valhalla('http://localhost').directions(locations=[[[8.58232, 51.57234]], waypoint, [7.15315, 53.632415]])
directions(locations: List[List[float]], profile: str, preference: str | None = None, options: dict | None = None, instructions: bool | None = False, language: str | None = None, directions_type: str | None = None, avoid_locations: List[List[float]] | None = None, avoid_polygons: List[List[List[float]]] | None = None, date_time: dict | None = None, alternatives: int | None = None, id: str | int | float | None = None, dry_run: bool | None = None, **kwargs)

Get directions between an origin point and a destination point.

For more information, visit https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/.

Use kwargs for any missing directions request options.

Parameters:
  • locations – The coordinates tuple the route should be calculated from in order of visit. Can be a list/tuple of [lon, lat] or Valhalla.WayPoint instance or a combination of both.

  • profile – Specifies the mode of transport to use when calculating directions. One of [“auto”, “auto_shorter” (deprecated), “bicycle”, “bus”, “hov”, “motor_scooter”, “motorcycle”, “multimodal”, “pedestrian”].

  • preference – Convenience argument to set the cost metric, one of [‘shortest’, ‘fastest’]. Note, that shortest is not guaranteed to be absolute shortest for motor vehicle profiles. It’s called preference to be inline with the already existing parameter in the ORS adapter.

  • options – Profiles can have several options that can be adjusted to develop the route path, as well as for estimating time along the path. Only specify the actual options dict, the profile will be filled automatically. For more information, visit: https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#costing-options

  • instructions – Whether to return turn-by-turn instructions. Named for compatibility with other providers. Valhalla’s parameter here is ‘narrative’.

  • language – The language of the narration instructions based on the IETF BCP 47 language tag string. One of [‘ca’, ‘cs’, ‘de’, ‘en’, ‘pirate’, ‘es’, ‘fr’, ‘hi’, ‘it’, ‘pt’, ‘ru’, ‘sl’, ‘sv’]. Default ‘en’.

  • directions_type – ‘none’: no instructions are returned. ‘maneuvers’: only maneuvers are returned. ‘instructions’: maneuvers with instructions are returned. Default ‘instructions’.

  • avoid_locations – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.

  • avoid_polygons – One or multiple exterior rings of polygons in the form of nested JSON arrays, e.g. [[[lon1, lat1], [lon2,lat2]],[[lon1,lat1],[lon2,lat2]]]. Roads intersecting these rings will be avoided during path finding. If you only need to avoid a few specific roads, it’s much more efficient to use avoid_locations. Valhalla will close open rings (i.e. copy the first coordingate to the last position).

  • date_time – This is the local date and time at the location. Field type: 0: Current departure time, 1: Specified departure time. Field value`: the date and time is specified in ISO 8601 format (YYYY-MM-DDThh:mm), local time. E.g. date_time = {type: 0, value: 2021-03-03T08:06:23}

  • alternatives (int) – The amount of alternatives to request. Note, with 1 you should get 2 routes. Also note that there may be no alternates or less alternates than what is requested and that alternates are not yet supported on routes with more than 2 locations. Default 0.

  • id – Name your route request. If id is specified, the naming will be sent thru to the response.

  • dry_run – Print URL and parameters without sending the request.

  • kwargs – any additional keyword arguments which will override parameters.

Returns:

A route from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction

expansion(locations: Sequence[float], profile: str, intervals: Sequence[int], skip_opposites: bool | None = None, expansion_properties: Sequence[str] | None = None, interval_type: str | None = 'time', options: dict | None = None, date_time: dict | None = None, id: str | None = None, dry_run: bool | None = None, **kwargs) Expansions

Gets the expansion tree for a range of time or distance values around a given coordinate.

For more information, visit https://valhalla.github.io/valhalla/api/expansion/api-reference/.

Parameters:
  • locations – One pair of lng/lat values. Takes the form [Longitude, Latitude].

  • profile – Specifies the mode of transport to use when calculating directions. One of [“auto”, “bicycle”, “multimodal”, “pedestrian”].

  • intervals – Time ranges to calculate isochrones for. In seconds or meters, depending on interval_type.

  • skip_opposites – If set to true the output won’t contain an edge’s opposing edge. Opposing edges can be thought of as both directions of one road segment. Of the two, we discard the directional edge with higher cost and keep the one with less cost.

  • expansion_properties – A JSON array of strings of the GeoJSON property keys you’d like to have in the response. One or multiple of “duration”, “distance”, “cost”, “edge_id”, “pre_edge_id”, “edge_status”. Note, that each additional property will increase the output size by minimum ~ 10%.

  • interval_type – Set ‘time’ for isochrones or ‘distance’ for equidistants. Default ‘time’.

  • options – Profiles can have several options that can be adjusted to develop the route path, as well as for estimating time along the path. Only specify the actual options dict, the profile will be filled automatically. For more information, visit: https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#costing-options

  • date_time

    This is the local date and time at the location. Field type: 0: Current departure time, 1: Specified departure time. Field value`: the date and time is specified in format YYYY-MM-DDThh:mm, local time.

    E.g. date_time = {type: 0, value: 2021-03-03T08:06}

  • id – Name your route request. If id is specified, the naming will be sent through to the response.

  • dry_run – Print URL and parameters without sending the request.

Returns:

An expansions object consisting of single line strings and their attributes (if specified).

static get_direction_params(locations, profile, preference=None, options=None, instructions=False, language=None, directions_type=None, avoid_locations=None, avoid_polygons=None, date_time=None, alternatives=None, id=None, **kwargs)

Builds and returns the router’s route parameters. It’s a separate function so that bindings can use routingpy’s functionality. See documentation of .directions().

static get_isochrone_params(locations, profile, intervals, interval_type, colors=None, polygons=None, denoise=None, generalize=None, preference=None, options=None, avoid_locations=None, avoid_polygons=None, date_time=None, show_locations=None, id=None, **kwargs)

Builds and returns the router’s route parameters. It’s a separate function so that bindings can use routingpy’s functionality. See documentation of .matrix().

static get_matrix_params(locations, profile, sources=None, destinations=None, preference=None, options=None, avoid_locations=None, avoid_polygons=None, date_time=None, id=None, **kwargs)

Builds and returns the router’s route parameters. It’s a separate function so that bindings can use routingpy’s functionality. See documentation of .matrix().

isochrones(locations: List[float], profile: str, intervals: List[int], interval_type: str | None = 'time', colors: List[str] | None = None, polygons: bool | None = None, denoise: float | None = None, generalize: float | None = None, preference: str | None = None, options: dict | None = None, language: str | None = None, directions_type: str | None = None, avoid_locations: List[List[float]] | None = None, avoid_polygons: List[List[List[float]]] | None = None, date_time: dict | None = None, show_locations: List[List[float]] | None = None, id: str | None = None, dry_run: bool | None = None, **kwargs)

Gets isochrones or equidistants for a range of time values around a given set of coordinates.

For more information, visit https://valhalla.github.io/valhalla/api/isochrone/api-reference/.

Use kwargs for any missing isochrones request options.

Parameters:
  • locations – One pair of lng/lat values. Takes the form [Longitude, Latitude].

  • profile – Specifies the mode of transport to use when calculating directions. One of [“auto”, “bicycle”, “multimodal”, “pedestrian”.

  • intervals – Time ranges to calculate isochrones for. In seconds or meters, depending on interval_type.

  • interval_type – Set ‘time’ for isochrones or ‘distance’ for equidistants. Default ‘time’.

  • colors – The color for the output of the contour. Specify it as a Hex value, but without the #, such as “color”:”ff0000” for red. If no color is specified, the isochrone service will assign a default color to the output.

  • polygons – Controls whether polygons or linestrings are returned in GeoJSON geometry. Default False.

  • denoise – Can be used to remove smaller contours. In range [0, 1]. A value of 1 will only return the largest contour for a given time value. A value of 0.5 drops any contours that are less than half the area of the largest contour in the set of contours for that same time value. Default 1.

  • generalize – A floating point value in meters used as the tolerance for Douglas-Peucker generalization. Note: Generalization of contours can lead to self-intersections, as well as intersections of adjacent contours.

  • preference – Convenience argument to set the cost metric, one of [‘shortest’, ‘fastest’]. Note, that shortest is not guaranteed to be absolute shortest for motor vehicle profiles. It’s called preference to be inline with the already existing parameter in the ORS adapter.

  • options – Profiles can have several options that can be adjusted to develop the route path, as well as for estimating time along the path. Only specify the actual options dict, the profile will be filled automatically. For more information, visit: https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#costing-options

  • language – The language of the narration instructions based on the IETF BCP 47 language tag string. One of [‘ca’, ‘cs’, ‘de’, ‘en’, ‘pirate’, ‘es’, ‘fr’, ‘hi’, ‘it’, ‘pt’, ‘ru’, ‘sl’, ‘sv’]. Default ‘en’.

  • avoid_locations – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.

  • avoid_polygons (List[List[List[float]]]) – One or multiple exterior rings of polygons in the form of nested JSON arrays, e.g. [[[lon1, lat1], [lon2,lat2]],[[lon1,lat1],[lon2,lat2]]]. Roads intersecting these rings will be avoided during path finding. If you only need to avoid a few specific roads, it’s much more efficient to use avoid_locations. Valhalla will close open rings (i.e. copy the first coordinate to the last position).

  • date_time

    This is the local date and time at the location. Field type: 0: Current departure time, 1: Specified departure time. Field value`: the date and time is specified in format YYYY-MM-DDThh:mm, local time.

    E.g. date_time = {type: 0, value: 2021-03-03T08:06}

  • id – Name your route request. If id is specified, the naming will be sent thru to the response.

  • dry_run – Print URL and parameters without sending the request.

Returns:

An isochrone with the specified range.

Return type:

routingpy.isochrone.Isochrones

matrix(locations: List[List[float]], profile: str, sources: List[int] | None = None, destinations: List[int] | None = None, preference: str | None = None, options: dict | None = None, avoid_locations: List[List[float]] | None = None, avoid_polygons: List[List[List[float]]] | None = None, date_time: dict | None = None, id: str | None = None, dry_run: bool | None = None, **kwargs)

Gets travel distance and time for a matrix of origins and destinations.

For more information, visit https://valhalla.github.io/valhalla/api/matrix/api-reference/.

Use kwargs for any missing matrix request options.

Parameters:
  • locations – Multiple pairs of lng/lat values.

  • profile – Specifies the mode of transport to use when calculating matrices. One of [“auto”, “bicycle”, “multimodal”, “pedestrian”].

  • sources – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • destinations – A list of indices that refer to the list of locations (starting with 0). If not passed, all indices are considered.

  • preference (str) – Convenience argument to set the cost metric, one of [‘shortest’, ‘fastest’]. Note, that shortest is not guaranteed to be absolute shortest for motor vehicle profiles. It’s called preference to be inline with the already existing parameter in the ORS adapter.

  • options – Profiles can have several options that can be adjusted to develop the route path, as well as for estimating time along the path. Only specify the actual options dict, the profile will be filled automatically. For more information, visit: https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#costing-options

  • avoid_locations – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.

  • avoid_polygons (List[List[List[float]]]) – One or multiple exterior rings of polygons in the form of nested JSON arrays, e.g. [[[lon1, lat1], [lon2,lat2]],[[lon1,lat1],[lon2,lat2]]]. Roads intersecting these rings will be avoided during path finding. If you only need to avoid a few specific roads, it’s much more efficient to use avoid_locations. Valhalla will close open rings (i.e. copy the first coordingate to the last position).

  • date_time – This is the local date and time at the location. Field type: 0: Current departure time, 1: Specified departure time. Field value`: the date and time is specified in format YYYY-MM-DDThh:mm, local time.

  • id – Name your route request. If id is specified, the naming will be sent through to the response.

  • dry_run – Print URL and parameters without sending the request.

Returns:

A matrix from the specified sources and destinations.

Return type:

routingpy.matrix.Matrix

optimized_directions(locations: List[List[float]], profile: str, preference: str | None = None, options: dict | None = None, instructions: bool | None = False, language: str | None = None, directions_type: str | None = None, avoid_locations: List[List[float]] | None = None, avoid_polygons: List[List[List[float]]] | None = None, date_time: dict | None = None, id: str | int | float | None = None, dry_run: bool | None = None, **kwargs)

Get directions for the optimized route, where the first and last location are not changed.

This uses a simple simulated annealing algorithm to solve the TSP. For more information, visit https://valhalla.github.io/valhalla/api/optimized/api-reference/.

Use kwargs for any missing optimized_directions request options.

Parameters:
  • locations – The coordinates tuple the optimized route should be calculated from. The order might change, depending on the solution of the TSP. Can be a list/tuple of [lon, lat] or Valhalla.WayPoint instance or a combination of both.

  • profile – Specifies the mode of transport to use when calculating directions. One of [“auto”, “auto_shorter” (deprecated), “bicycle”, “bus”, “hov”, “motor_scooter”, “motorcycle”, “multimodal”, “pedestrian”].

  • preference – Convenience argument to set the cost metric, one of [‘shortest’, ‘fastest’]. Note, that shortest is not guaranteed to be absolute shortest for motor vehicle profiles. It’s called preference to be inline with the already existing parameter in the ORS adapter.

  • options – Profiles can have several options that can be adjusted to develop the route path, as well as for estimating time along the path. Only specify the actual options dict, the profile will be filled automatically. For more information, visit: https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#costing-options

  • instructions – Whether to return turn-by-turn instructions. Named for compatibility with other providers. Valhalla’s parameter here is ‘narrative’.

  • language – The language of the narration instructions based on the IETF BCP 47 language tag string. One of [‘ca’, ‘cs’, ‘de’, ‘en’, ‘pirate’, ‘es’, ‘fr’, ‘hi’, ‘it’, ‘pt’, ‘ru’, ‘sl’, ‘sv’]. Default ‘en’.

  • directions_type – ‘none’: no instructions are returned. ‘maneuvers’: only maneuvers are returned. ‘instructions’: maneuvers with instructions are returned. Default ‘instructions’.

  • avoid_locations – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.

  • avoid_polygons – One or multiple exterior rings of polygons in the form of nested JSON arrays, e.g. [[[lon1, lat1], [lon2,lat2]],[[lon1,lat1],[lon2,lat2]]]. Roads intersecting these rings will be avoided during path finding. If you only need to avoid a few specific roads, it’s much more efficient to use avoid_locations. Valhalla will close open rings (i.e. copy the first coordingate to the last position).

  • date_time – This is the local date and time at the location. Field type: 0: Current departure time, 1: Specified departure time. Field value`: the date and time is specified in ISO 8601 format (YYYY-MM-DDThh:mm), local time. E.g. date_time = {type: 0, value: 2021-03-03T08:06:23}

  • id – Name your route request. If id is specified, the naming will be sent thru to the response.

  • dry_run – Print URL and parameters without sending the request.

  • kwargs – any additional keyword arguments which will override parameters.

Returns:

A route optimized by TSP from provided coordinates and restrictions.

Return type:

routingpy.optimized.OptimizedDirection

raster(locations: List[float], profile: str, intervals: List[int], interval_type: str | None = 'time', colors: List[str] | None = None, polygons: bool | None = None, denoise: float | None = None, generalize: float | None = None, preference: str | None = None, options: dict | None = None, avoid_locations: List[List[float]] | None = None, avoid_polygons: List[List[List[float]]] | None = None, date_time: dict | None = None, show_locations: List[List[float]] | None = None, id: str | None = None, dry_run: bool | None = None, **kwargs)

For parameters see docs for isochrones.

Returns isochrones/isodistances as GeoTIFF

trace_attributes(locations: Sequence[Sequence[float] | Waypoint] | None = None, profile: str = 'bicycle', shape_match: str = 'walk_or_snap', encoded_polyline: str | None = None, filters: List[str] | None = None, filters_action: str | None = None, options: dict | None = None, dry_run: bool | None = None, **kwargs) MatchedResults

Map-matches the input locations to form a route on the Valhalla base network and returns detailed attribution for encountered edges and nodes.

For more information, visit https://valhalla.readthedocs.io/en/latest/api/map-matching/api-reference/.

Parameters:
  • locations – One pair of lng/lat values or Waypoint. Takes the form [Longitude, Latitude].

  • profile – Specifies the mode of transport to use when calculating directions. One of [“auto”, “bicycle”, “multimodal”, “pedestrian”].

  • shape_match – It allows some control of the matching algorithm based on the type of input. One of [“edge_walk”, “map_snap”, “walk_or_snap”]. See for full reference: https://valhalla.github.io/valhalla/api/map-matching/api-reference/#shape-matching-parameters

  • encoded_polyline – The encoded polyline string with precision 6.

  • filters – A list of response object to either include or exclude, depending on the filter_action attribute

  • filters_action – Whether to include or exclude the filters. One of [“include”, “exclude”].

  • options – Profiles can have several options that can be adjusted to develop the route path, as well as for estimating time along the path. Only specify the actual options dict, the profile will be filled automatically. For more information, visit: https://valhalla.github.io/valhalla/api/turn-by-turn/api-reference/#costing-options

  • dry_run – Print URL and parameters without sending the request.

Raises:

ValueError if ‘locations’ and ‘encoded_polyline’ was specified

Returns:

A MatchedResults object with matched edges and points set.

Client

class routingpy.client_default.Client(base_url, user_agent=None, timeout=DEFAULT, retry_timeout=None, retry_over_query_limit=None, skip_api_error=None, **kwargs)

Default client class for requests handling, which is passed to each router. Uses the requests package.

__init__(base_url, user_agent=None, timeout=DEFAULT, retry_timeout=None, retry_over_query_limit=None, skip_api_error=None, **kwargs)
Parameters:
  • base_url (string) – The base URL for the request. All routers must provide a default. Should not have a trailing slash.

  • user_agent (string) – User-Agent to send with the requests to routing API. Overrides options.default_user_agent.

  • timeout (int) – Combined connect and read timeout for HTTP requests, in seconds. Specify “None” for no timeout.

  • retry_timeout (int) – Timeout across multiple retriable requests, in seconds.

  • retry_over_query_limit (bool) – If True, client will not raise an exception on HTTP 429, but instead jitter a sleeping timer to pause between requests until HTTP 200 or retry_timeout is reached.

  • skip_api_error (bool) – Continue with batch processing if a routingpy.exceptions.RouterApiError is encountered (e.g. no route found). If False, processing will discontinue and raise an error. Default False.

  • kwargs (dict) – Additional arguments, such as headers or proxies.

property req

Holds the requests.PreparedRequest property for the last request.

Data

class routingpy.direction.Directions(directions=None, raw=None)

Contains a list of Direction, when the router returned multiple alternative routes, and the complete raw response, which can be accessed via the property raw.

property raw: dict | None

Returns the directions raw, unparsed response. For details, consult the routing engine’s API documentation. :rtype: dict or None

class routingpy.direction.Direction(geometry=None, duration=None, distance=None, raw=None)

Contains a parsed directions’ response. Access via properties geometry, duration and distance.

property distance: int

The distance of the entire trip in meters.

Return type:

int

property duration: int

The duration of the entire trip in seconds.

Return type:

int

property geometry: List[List[float]] | None

The geometry of the route as [[lon1, lat1], [lon2, lat2], …] list.

Return type:

list or None

property km: float

The distance of the entire trip in kilometers.

Return type:

float

property mi: float

The distance of the entire trip in miles.

Return type:

float

class routingpy.isochrone.Isochrones(isochrones=None, raw=None)

Contains a list of Isochrone, which can be iterated over or accessed by index. The property ¸`raw`` contains the complete raw response of the isochrones request.

property raw: dict | None

Returns the isochrones’ raw, unparsed response. For details, consult the routing engine’s API documentation.

Return type:

dict or None

class routingpy.isochrone.Isochrone(geometry=None, interval=None, center=None, interval_type=None)

Contains a parsed single isochrone response. Access via properties geometry, interval, center, interval_type.

property center: List[float] | Tuple[float] | None

The center coordinate in [lon, lat] of the isochrone. Might deviate from the input coordinate. Not available for all routing engines (e.g. GraphHopper, Mapbox OSRM or Valhalla). In this case, it will use the location from the user input.

Return type:

list of float or None

property geometry: List[List[float]] | None

The geometry of the isochrone as [[lon1, lat1], [lon2, lat2], …] list.

Return type:

list or None

class routingpy.matrix.Matrix(durations=None, distances=None, raw=None)

Contains a parsed matrix response. Access via properties geometry and raw.

property distances: List[List[float | None]] | None

The distance matrix as list akin to:

[
    [
        duration(origin1-destination1),
        duration(origin1-destination2),
        duration[origin1-destination3),
        ...
    ],
    [
        duration(origin2-destination1),
        duration(origin2-destination2),
        duration[origin3-destination3),
        ...
    ],
    ...
]

The distances are in meters.

Return type:

list or None

property durations: List[List[float | None]] | None

The durations matrix as list akin to:

[
    [
        duration(origin1-destination1),
        duration(origin1-destination2),
        duration[origin1-destination3),
        ...
    ],
    [
        duration(origin2-destination1),
        duration(origin2-destination2),
        duration[origin3-destination3),
        ...
    ],
    ...
]
Return type:

list or None

property raw: dict | None

Returns the matrices raw, unparsed response. For details, consult the routing engine’s API documentation.

Return type:

dict or None

class routingpy.expansion.Expansions(edges: List[Edge] | None = None, center: List[float] | Tuple[float] | None = None, interval_type: str | None = None, raw: dict | None = None)

Contains a list of Edge, which can be iterated over or accessed by index. The property ¸`raw`` contains the complete raw response of the expansion request.

property center: List[float] | Tuple[float] | None

The center coordinate in [lon, lat] of the expansion, which is the location from the user input.

Return type:

list of float or None

property raw: dict | None
Returns the expansion’s raw, unparsed response. For details, consult the documentation

at https://valhalla.readthedocs.io/en/latest/api/expansion/api-reference/.

Return type:

dict or None

class routingpy.expansion.Edge(geometry=None, distance=None, duration=None, cost=None, edge_id=None, pred_edge_id=None, edge_status=None)

Contains a parsed single line string of an edge and its attributes, if specified in the request. Access via properties geometry, distance duration, cost, edge_id, pred_edge_id, edge_status.

property cost: int | None

The accumulated cost for the edge in order of graph traversal.

Return type:

int or None

property distance: int | None

The accumulated distance in meters for the edge in order of graph traversal.

Return type:

int or None

property duration: int | None

The accumulated duration in seconds for the edge in order of graph traversal.

Return type:

int or None

property edge_id: int | None

The internal edge IDs for each edge in order of graph traversal.

Return type:

int or None

property geometry: List[List[float]] | None

The geometry of the edge as [[lon1, lat1], [lon2, lat2]] list.

Return type:

list or None

property status: str | None

The edge states for each edge in order of graph traversal. Can be one of “r” (reached), “s” (settled), “c” (connected).

Return type:

str or None

class routingpy.optimized.OptimizedDirection(geometry=None, duration=None, distance=None, original_indices=None, raw=None)

Contains a parsed optimized_directions’s response. Access via properties geometry, duration, distance and original_index.

property distance: int

The distance of the entire trip in meters.

Return type:

int

property duration: int

The duration of the entire trip in seconds.

Return type:

int

property geometry: List[List[float]] | None

The geometry of the route as [[lon1, lat1], [lon2, lat2], …] list.

Return type:

list or None

property km: float

The distance of the entire trip in kilometers.

Return type:

float

property mi: float

The distance of the entire trip in miles.

Return type:

float

original_index(reordered_index: int) int

The original (input) location index for the reordered_index element of the response locations.

Return type:

int

routingpy.utils.decode_polyline5(polyline, is3d=False, order='lnglat')

Decodes an encoded polyline string which was encoded with a precision of 5.

Parameters:
  • polyline (str) – An encoded polyline, only the geometry.

  • is3d (bool) – Specifies if geometry contains Z component. Currently only GraphHopper and OpenRouteService support this. Default False.

  • order (str) – Specifies the order in which the coordinates are returned. Options: latlng, lnglat. Defaults to ‘lnglat’.

Returns:

List of decoded coordinates with precision 5.

Return type:

list

routingpy.utils.decode_polyline6(polyline, is3d=False, order='lnglat')

Decodes an encoded polyline string which was encoded with a precision of 6.

Parameters:
  • polyline (str) – An encoded polyline, only the geometry.

  • is3d (bool) – Specifies if geometry contains Z component. Currently only GraphHopper and OpenRouteService support this. Default False.

  • order (str) – Specifies the order in which the coordinates are returned. Options: latlng, lnglat. Defaults to ‘lnglat’.

Returns:

List of decoded coordinates with precision 6.

Return type:

list

Exceptions

class routingpy.exceptions.RouterError(status, message=None)

Bases: Exception

Represents an exception returned by the remote or local API.

class routingpy.exceptions.RouterApiError(status, message=None)

Bases: RouterError

Represents an exception returned by a routing engine, i.e. 400 <= HTTP status code <= 500

class routingpy.exceptions.RouterServerError(status, message=None)

Bases: RouterError

Represents an exception returned by a server, i.e. 500 <= HTTP

class routingpy.exceptions.RouterNotFound

Bases: Exception

Represents an exception raised when router can not be found by name.

class routingpy.exceptions.Timeout

Bases: Exception

The request timed out.

class routingpy.exceptions.RetriableRequest

Bases: Exception

Signifies that the request can be retried.

class routingpy.exceptions.OverQueryLimit(status, message=None)

Bases: RouterError, RetriableRequest

Signifies that the request failed because the client exceeded its query rate limit.

Normally we treat this as a retriable condition, but we allow the calling code to specify that these requests should not be retried.

Changelog

See our Changelog.md.