Welcome to routingpy’s documentation!

Documentation

https://routingpy.readthedocs.io/

Source Code

https://github.com/gis-ops/routing-py

Issue Tracker

https://github.com/gis-ops/routing-py/issues

PyPI

https://pypi.org/project/routingpy

MyBinder Interactive Examples

https://mybinder.org/v2/gh/gis-ops/routing-py/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 3.8, 3.9, 3.10, 3.11 and PyPy3 (#60).

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.heremaps.HereMaps, routingpy.routers.mapbox_osrm.MapBoxOSRM, routingpy.routers.mapbox_valhalla.MapBoxValhalla, 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 MapboxValhalla
>>> options.default_user_agent = 'amazing_routing_app'
>>> options.default_proxies = {'https': '129.125.12.0'}
>>> router = MapboxValhalla(my_key)
>>> print(router.client.headers)
{'User-Agent': 'amazing_routing_app', 'Content-Type': 'application/json'}
>>> 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/vNone'

Google

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

Performs requests to the Google API services.

__init__(api_key: str, user_agent: typing.Optional[str] = None, timeout: typing.Optional[int] = DEFAULT, retry_timeout: typing.Optional[int] = None, retry_over_query_limit=True, skip_api_error: typing.Optional[bool] = 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: Optional[bool] = None, avoid: Optional[List[str]] = None, optimize: Optional[bool] = None, language: Optional[str] = None, region: Optional[str] = None, units: Optional[str] = None, arrival_time: Optional[int] = None, departure_time: Optional[int] = None, traffic_model: Optional[str] = None, transit_mode: Optional[Union[List[str], Tuple[str]]] = None, transit_routing_preference: Optional[str] = None, dry_run: Optional[bool] = None)

Get directions between an origin point and a destination point.

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

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/intro#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/intro#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: Optional[Union[List[int], Tuple[int]]] = None, destinations: Optional[Union[List[int], Tuple[int]]] = None, avoid: Optional[List[str]] = None, language: Optional[str] = None, region: Optional[str] = None, units: Optional[str] = None, arrival_time: Optional[int] = None, departure_time: Optional[int] = None, traffic_model: Optional[str] = None, transit_mode: Optional[Union[List[str], Tuple[str]]] = None, transit_routing_preference: Optional[str] = None, dry_run: Optional[bool] = 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/intro#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/intro#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: typing.Optional[str] = None, base_url: typing.Optional[str] = 'https://graphhopper.com/api/1', user_agent: typing.Optional[str] = None, timeout: typing.Optional[int] = DEFAULT, retry_timeout: typing.Optional[int] = None, retry_over_query_limit: typing.Optional[bool] = False, skip_api_error: typing.Optional[bool] = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the Graphhopper API services.

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

Initializes an graphhopper client.

Parameters
directions(locations: Union[List[List[float]], Tuple[Tuple[float]]], profile: str, format: Optional[str] = None, optimize: Optional[bool] = None, instructions: Optional[bool] = None, locale: Optional[str] = None, elevation: Optional[bool] = None, points_encoded: Optional[bool] = True, calc_points: Optional[bool] = None, debug: Optional[bool] = None, point_hints: Optional[List[str]] = None, details: Optional[List[str]] = None, ch_disable: Optional[bool] = None, custom_model: Optional[dict] = None, headings: Optional[List[int]] = None, heading_penalty: Optional[int] = None, pass_through: Optional[bool] = None, algorithm: Optional[str] = None, round_trip_distance: Optional[int] = None, round_trip_seed: Optional[int] = None, alternative_route_max_paths: Optional[int] = None, alternative_route_max_weight_factor: Optional[float] = None, alternative_route_max_share_factor: Optional[float] = None, dry_run: Optional[bool] = None, snap_preventions: Optional[List[str]] = None, curbsides: Optional[List[str]] = 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/#operation/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/#section/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.

New 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,

New 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: Union[Tuple[float], List[float]], profile: str, intervals: Union[List[int], Tuple[int]], type: Optional[str] = 'json', buckets: Optional[int] = 1, interval_type: Optional[str] = 'time', reverse_flow: Optional[bool] = None, debug: Optional[bool] = None, dry_run: Optional[bool] = 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/#tag/Isochrone-API.

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: Union[List[Union[List[float], Tuple[float]]], Tuple[Union[List[float], Tuple[float]]]], profile: str, sources: Optional[List[int]] = None, destinations: Optional[List[int]] = None, out_array: Optional[List[str]] = ['times', 'distances'], debug=None, dry_run: Optional[bool] = 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/#tag/Matrix-API.

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 https://graphhopper.com/api/1/docs/supported-vehicle-profiles/Default. 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

HereMaps

class routingpy.routers.HereMaps(app_id: typing.Optional[str] = None, app_code: typing.Optional[str] = None, user_agent: typing.Optional[str] = None, timeout: typing.Optional[int] = DEFAULT, retry_timeout: typing.Optional[int] = None, retry_over_query_limit: typing.Optional[bool] = False, skip_api_error: typing.Optional[bool] = None, api_key: typing.Optional[str] = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the HERE Maps API services.

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

Initializes a HERE Maps client.

Parameters
class RoutingMode(mode_type='fastest', mode_transport_type='car', mode_traffic=None, features=None)

Optionally construct the routing profile from this class with additional attributes. https://developer.here.com/documentation/routing/topics/resource-param-type-routing-mode.html

Example

>>> profile = HereMaps.RoutingMode(mode_type='shortest', mode_transport_type='truck', mode_traffic=True, features={'motorway': -2})
>>> route = HereMaps(api_key).directions(locations=location_list, profile=profile)
class Waypoint(position, waypoint_type=None, stopover_duration=None, transit_radius='', user_label='', heading='')

Constructs a waypoint with additional information. https://developer.here.com/documentation/routing/topics/resource-param-type-waypoint.html

Example:

>>> waypoint = HereMaps.Waypoint(position=[8.15315, 52.53151], waypoint_type='passThrough', stopover_duration=120, transit_radius=500)
>>> route = HereMaps(api_key).directions(locations=[[[8.58232, 51.57234]], waypoint, [7.15315, 53.632415]])
directions(locations: List[List[float]], profile: str, mode_type: Optional[str] = 'fastest', format: Optional[str] = 'json', request_id: Optional[str] = None, avoid_areas: Optional[List[List[List[float]]]] = None, avoid_links: Optional[List[str]] = None, avoid_seasonal_closures: Optional[bool] = None, avoid_turns: Optional[str] = None, allowed_zones: Optional[List[int]] = None, exclude_zones: Optional[List[int]] = None, exclude_zone_types: Optional[List[str]] = None, exclude_countries: Optional[List[str]] = None, arrival: Optional[str] = None, departure: Optional[str] = None, alternatives: Optional[int] = None, metric_system: Optional[str] = None, view_bounds: Optional[Union[List[float], Tuple[float]]] = None, resolution: Optional[dict] = None, instruction_format: Optional[str] = None, language: Optional[str] = None, json_attributes: Optional[int] = None, json_callback: Optional[str] = None, representation: Optional[List[str]] = None, route_attributes: Optional[List[str]] = ['waypoints', 'summary', 'shape', 'boundingBox', 'legs'], leg_attributes: Optional[List[str]] = None, maneuver_attributes: Optional[List[str]] = None, link_attributes: Optional[List[str]] = None, line_attributes: Optional[List[str]] = None, generalization_tolerances: Optional[List[float]] = None, vehicle_type: Optional[str] = None, license_plate: Optional[str] = None, max_number_of_changes: Optional[int] = None, avoid_transport_types: Optional[List[str]] = None, walk_time_multiplier: Optional[float] = None, walk_speed: Optional[float] = None, walk_radius: Optional[int] = None, combine_change: Optional[bool] = None, truck_type: Optional[str] = None, trailers_count: Optional[int] = None, shipped_hazardous_goods: Optional[List[str]] = None, limited_weight: Optional[int] = None, weight_per_axle: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, length: Optional[int] = None, tunnel_category: Optional[List[str]] = None, truck_restriction_penalty: Optional[str] = None, return_elevation: Optional[bool] = None, consumption_model: Optional[str] = None, custom_consumption_details: Optional[str] = None, speed_profile: Optional[str] = None, dry_run: Optional[bool] = None, **directions_kwargs)

Get directions between an origin point and a destination point.

Use direction_kwargs for any missing directions request options.

For more information, https://developer.here.com/documentation/routing/topics/resource-calculate-route.html.

Parameters
  • locations (list of list or list of HereMaps.Waypoint) – The coordinates tuple the route should be calculated from in order of visit. Can be a list/tuple of [lon, lat] or HereMaps.Waypoint instance or a combination of those. For further explanation, see https://developer.here.com/documentation/routing/topics/resource-param-type-waypoint.html

  • profile (str or HereMaps.RoutingMode) – Specifies the routing mode of transport and further options. Can be a str and one of [car, pedestrian, carHOV, publicTransport, publicTransportTimeTable, truck, bicycle] or HereMaps.RoutingMode. https://developer.here.com/documentation/routing/topics/resource-param-type-routing-mode.html

  • mode_type (str) – RoutingType relevant to calculation. One of [fastest, shortest, balanced]. Default fastest. https://developer.here.com/documentation/routing/topics/resource-param-type-routing-mode.html#ariaid-title2

  • format (str) – Currently only “json” supported.

  • request_id (str) – Clients may pass in an arbitrary string to trace request processing through the system. The RequestId is mirrored in the MetaInfo element of the response structure.

  • avoid_areas (list of list of list) – Areas which the route must not cross. Array of BoundingBox. Example with 2 bounding boxes https://developer.here.com/documentation/routing/topics/resource-param-type-bounding-box.html

  • avoid_links (list of str) – Links which the route must not cross. The list of LinkIdTypes.

  • avoid_seasonal_closures (bool) – The optional avoid seasonal closures boolean flag can be specified to avoid usage of seasonally closed links. Examples of seasonally closed links are roads that may be closed during the winter due to weather conditions or ferries that may be out of operation for the season (based on past closure dates).

  • avoid_turns (str) – List of turn types that the route should avoid. Defaults to empty list. https://developer.here.com/documentation/routing/topics/resource-type-enumerations.html

  • allowed_zones (list of int) – Identifiers of zones where routing engine should not take zone restrictions into account (for example in case of a special permission to access a restricted environmental zone). https://developer.here.com/documentation/routing/topics/resource-get-routing-zones.html

  • exclude_zones (list of int) – Identifiers of zones which the route must not cross under any circumstances. https://developer.here.com/documentation/routing/topics/resource-get-routing-zones.html

  • exclude_zone_types (list of str) – List of zone types which the route must not cross under any circumstances. https://developer.here.com/documentation/routing/topics/resource-type-enumerations.html #resource-type-enumerations__enum-routing-zone-type-type

  • exclude_countries (list of str) – Countries that must be excluded from route calculation.

  • departure (str) – Time when travel is expected to start. Traffic speed and incidents are taken into account when calculating the route (note that in case of a past departure time the historical traffic is limited to one year). You can use now to specify the current time. Specify either departure or arrival, not both. When the optional timezone offset is not specified, the time is assumed to be the local. Formatted as iso time, e.g. 2018-07-04T17:00:00+02.

  • arrival (str) – Time when travel is expected to end. Specify either departure or arrival, not both. When the optional timezone offset is not specified, the time is assumed to be the local. Formatted as iso time, e.g. 2018-07-04T17:00:00+02.

  • alternatives (int) – Maximum number of alternative routes that will be calculated and returned. Alternative routes can be unavailable, thus they are not guaranteed to be returned. If at least one via point is used in a route request, returning alternative routes is not supported. 0 stands for “no alternative routes”, i.e. only best route is returned.

  • metric_system (str) – Defines the measurement system used in instruction text. When imperial is selected, units used are based on the language specified in the request. Defaults to metric when not specified.

  • view_bounds (list or tuple) – If the view bounds are given in the request then only route shape points which fit into these bounds will be returned. The route shape beyond the view bounds is reduced to the points which are referenced by links, legs or maneuvers.

  • resolution (dict) – Specifies the resolution of the view and a possible snap resolution in meters per pixel in the response. You must specify a whole, positive integer. If you specify only one value, then this value defines the view resolution only. You can use snap resolution to adjust waypoint links to the resolution of the client display. e.g. {‘viewresolution’: 300,’snapresolution’: 300}

  • instruction_format (str) – Defines the representation format of the maneuver’s instruction text. Html or txt.

  • language (str) – A list of languages for all textual information, the first supported language is used. If there are no matching supported languages the response is an error. Defaults to en-us. https://developer.here.com/documentation/routing/topics/resource-param-type-languages.html#languages

  • json_attributes (int) – Flag to control JSON output. Combine parameters by adding their values. https://developer.here.com/documentation/routing/topics/resource-param-type-json-representation.html

  • json_callback (str) – Name of a user-defined function used to wrap the JSON response.

  • representation (list of str) – Define which elements are included in the response as part of the data representation of the route. https://developer.here.com/documentation/routing/topics/resource-param-type-route-representation-options.html#type-route-represenation-mode

  • route_attributes (list of str) – Define which attributes are included in the response as part of the data representation of the route. Defaults to waypoints, summary, legs and additionally lines if publicTransport or publicTransportTimeTable mode is used. https://developer.here.com/documentation/routing/topics/resource-param-type-route-representation-options.html#type-route-attribute

  • leg_attributes (list of str) – Define which attributes are included in the response as part of the data representation of the route legs. Defaults to maneuvers, waypoint, length, travelTime. https://developer.here.com/documentation/routing/topics/resource-param-type-route-representation-options.html#type-route-leg-attribute

  • maneuver_attributes (list of str) – Define which attributes are included in the response as part of the data representation of the route maneuvers. Defaults to position, length, travelTime. https://developer.here.com/documentation/routing/topics/resource-param-type-route-representation-options.html#type-maneuver-attribute

  • link_attributes (list of str) – Define which attributes are included in the response as part of the data representation of the route links. Defaults to shape, speedLimit. https://developer.here.com/documentation/routing/topics/resource-param-type-route-representation-options.html#type-route-link-attribute

  • line_attributes (list of str) – Sequence of attribute keys of the fields that are included in public transport line elements. If not specified, defaults to lineForeground, lineBackground. https://developer.here.com/documentation/routing/topics/resource-param-type-route-representation-options.html#type-public-transport-line-attribute

  • generalization_tolerances (list of float) – Specifies the desired tolerances for generalizations of the base route geometry. Tolerances are given in degrees of longitude or latitude on a spherical approximation of the Earth. One meter is approximately equal to 0:00001 degrees at typical latitudes.

  • vehicle_type (str) – Specifies type of vehicle engine and average fuel consumption, which can be used to estimate CO2 emission for the route summary. https://developer.here.com/documentation/routing/topics/resource-param-type-vehicle-type.html

  • license_plate (str) – Specifies fragments of vehicle’s license plate number. The last character is currently the only supported fragment type. The license plate parameter enables evaluation of license plate based vehicle restrictions like odd/even scheme in Indonesia.

  • max_number_of_changes (int) – Restricts number of changes in a public transport route to a given value. The parameter does not filter resulting alternatives. Instead, it affects route calculation so that only routes containing at most the given number of changes are considered. The provided value must be between 0 and 10.

  • avoid_transport_types (list of str) – Public transport types that shall not be included in the response route. Please refer to Enumeration Types for a list of supported values. https://developer.here.com/documentation/routing/topics/resource-type-enumerations.html

  • walk_time_multiplier (float) – Allows to prefer or avoid public transport routes with longer walking distances. A value > 1.0 means a slower walking speed and will prefer routes with less walking distance. The provided value must be between 0.01 and 100.

  • walk_speed (float) – Specifies speed which will be used by a service as a walking speed for pedestrian routing (meters per second). This parameter affects pedestrian, publicTransport and publicTransportTimetable modes. The provided value must be between 0.5 and 2.

  • walk_radius (int) – Allows the user to specify a maximum distance to the start and end stations of a public transit route. Only valid for publicTransport and publicTransportTimetable routes. The provided value must be between 0 and 6000.

  • combine_change (bool) – Enables the change maneuver in the route response, which indicates a public transit line change. In the absence of this maneuver, each line change is represented with a pair of subsequent enter and leave maneuvers. We recommend enabling combineChange behavior wherever possible, to simplify client-side development.

  • truck_type (str) – Truck routing only, specifies the vehicle type. Defaults to truck.

  • trailers_count (int) – Truck routing only, specifies number of trailers pulled by a vehicle. The provided value must be between 0 and 4. Defaults to 0.

  • shipped_hazardous_goods (list of str) – Truck routing only, list of hazardous materials in the vehicle. Please refer to the enumeration type HazardousGoodTypeType for available values. Note the value allhazardousGoods does not apply to the request parameter. https://developer.here.com/documentation/routing/topics/resource-type-enumerations.html#resource-type-enumerations__enum-hazardous-good-type-type

  • limited_weight (int) – Truck routing only, vehicle weight including trailers and shipped goods, in tons. The provided value must be between 0 and 1000.

  • weight_per_axle (int) – Truck routing only, vehicle weight per axle in tons. The provided value must be between 0 and 1000.

  • height (int) – Truck routing only, vehicle height in meters. The provided value must be between 0 and 50.

  • width (int) – Truck routing only, vehicle width in meters. The provided value must be between 0 and 50.

  • length (int) – Truck routing only, vehicle length in meters. The provided value must be between 0 and 300.

  • tunnel_category (list of str) – Truck routing only, specifies the tunnel category to restrict certain route links. The route will pass only through tunnels of a less strict category.

  • truck_restriction_penalty (str) – Truck routing only, specifies the penalty type on violated truck restrictions. Defaults to strict. Refer to the enumeration type TruckRestrictionPenaltyType for details on available values. https://developer.here.com/documentation/routing/topics/resource-type-enumerations.html#resource-type-enumerations__enum-truck-restriction-penalty-type

  • return_elevation (bool) – If set to true, all shapes inside routing response will consist of 3 values instead of 2. Third value will be elevation. If there are no elevation data available for given shape point, elevation will be interpolated from surrounding points. In case there is no elevation data available for any of the shape points, elevation will be 0.0. If jsonattributes=32, elevation cannot be returned.

  • consumption_model (str) – If you request information on consumption, you must provide a consumption model. The possible values are default and standard. When you specify the value standard, you must provide additional information in the query parameter customconsumptiondetails

  • custom_consumption_details (str) – Provides vehicle specific information for use in the consumption model. This information can include such things as the amount of energy consumed while travelling at a given speed. https://developer.here.com/documentation/routing/topics/resource-param-type-custom-consumption-details.html#type-standard

  • speed_profile (str) – Specifies the speed profile variant for a given routing mode. The speed profile affects travel time estimation as well as roads evaluation when computing the fastest route. Note that computed routes might differ depending on a used profile. https://developer.here.com/documentation/routing/topics/resource-param-type-speed-profile-type.html

  • 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], mode_type: Optional[str] = 'fastest', interval_type: Optional[str] = 'time', format: Optional[str] = 'json', center_type: Optional[str] = 'start', request_id: Optional[str] = None, arrival: Optional[str] = None, departure: Optional[str] = None, single_component: Optional[bool] = None, resolution: Optional[int] = None, max_points: Optional[int] = None, quality: Optional[int] = None, json_attributes: Optional[int] = None, json_callback=None, truck_type: Optional[str] = None, trailers_count: Optional[int] = None, shipped_hazardous_goods: Optional[List[str]] = None, limited_weight: Optional[int] = None, weight_per_axle: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, length: Optional[int] = None, tunnel_category: Optional[List[str]] = None, consumption_model: Optional[str] = None, custom_consumption_details: Optional[str] = None, speed_profile: Optional[str] = None, dry_run: Optional[bool] = None, **isochrones_kwargs)

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

Use isochrones_kwargs for any missing isochrones request options.

For more information, https://developer.here.com/documentation/routing/topics/resource-calculate-isoline.html.

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

  • profile (str or HereMaps.RoutingMode) – Specifies the routing mode of transport and further options. Can be a str or HereMaps.RoutingMode https://developer.here.com/documentation/routing/topics/resource-param-type-routing-mode.html

  • intervals (list of int) – Range of isoline. Several comma separated values can be specified. The unit is defined by parameter rangetype.

  • mode_type (str) – RoutingType relevant to calculation. One of [fastest, shortest, balanced]. Default fastest. https://developer.here.com/documentation/routing/topics/resource-param-type-routing-mode.html#ariaid-title2

  • interval_type (str) – Specifies type of range. Possible values are distance, time, consumption. For distance the unit is meters. For time the unit is seconds. For consumption, it is defined by consumption model

  • format (str) – Currently only “json” supported.

  • center_type (str) – If ‘start’ then the isoline will cover all roads which can be reached from this point within given range. It cannot be used in combination with destination parameter. If ‘destination’ Center of the isoline request. Isoline will cover all roads from which this point can be reached within given range. It cannot be used in combination with start parameter.

  • departure (str) – Time when travel is expected to start. Traffic speed and incidents are taken into account when calculating the route (note that in case of a past departure time the historical traffic is limited to one year). You can use now to specify the current time. Specify either departure or arrival, not both. When the optional timezone offset is not specified, the time is assumed to be the local. Formatted as iso time, e.g. 2018-07-04T17:00:00+02.

  • arrival (str) – Time when travel is expected to end. Specify either departure or arrival, not both. When the optional timezone offset is not specified, the time is assumed to be the local. Formatted as iso time, e.g. 2018-07-04T17:00:00+02.

  • single_component (bool) – If set to true the isoline service will always return single polygon, instead of creating a separate polygon for each ferry separated island. Default value is false.

  • resolution (int) – Allows to specify level of detail needed for the isoline polygon. Unit is meters per pixel. Higher resolution may cause increased response time from the service.

  • max_points (int) – Allows to limit amount of points in the returned isoline. If isoline consists of multiple components, sum of points from all components is considered. Each component will have at least 2 points, so it is possible that more points than maxpoints value will be returned. This is in case when 2 * number of components is higher than maxpoints. Enlarging number of maxpoints may cause increased response time from the service.

  • quality (int) – Allows to reduce the quality of the isoline in favor of the response time. Allowed values are 1, 2, 3. Default value is 1, and it is the best quality.

  • json_attributes (int) – Flag to control JSON output. Combine parameters by adding their values. https://developer.here.com/documentation/routing/topics/resource-param-type-json-representation.html

  • truck_type (str) – Truck routing only, specifies the vehicle type. Defaults to truck.

  • trailers_count (int) – Truck routing only, specifies number of trailers pulled by a vehicle. The provided value must be between 0 and 4. Defaults to 0.

  • shipped_hazardous_goods (list of str) – Truck routing only, list of hazardous materials in the vehicle. Please refer to the enumeration type HazardousGoodTypeType for available values. Note the value allhazardousGoods does not apply to the request parameter. https://developer.here.com/documentation/routing/topics/resource-type-enumerations.html#resource-type-enumerations__enum-hazardous-good-type-type

  • limited_weight (int) – Truck routing only, vehicle weight including trailers and shipped goods, in tons. The provided value must be between 0 and 1000.

  • weight_per_axle (int) – Truck routing only, vehicle weight per axle in tons. The provided value must be between 0 and 1000.

  • height (int) – Truck routing only, vehicle height in meters. The provided value must be between 0 and 50.

  • width (int) – Truck routing only, vehicle width in meters. The provided value must be between 0 and 50.

  • length (int) – Truck routing only, vehicle length in meters. The provided value must be between 0 and 300.

  • tunnel_category (list of str) – Truck routing only, specifies the tunnel category to restrict certain route links. The route will pass only through tunnels of a less strict category.

  • consumption_model (str) – If you request information on consumption, you must provide a consumption model. The possible values are default and standard. When you specify the value standard, you must provide additional information in the query parameter custom consumption details

  • custom_consumption_details (str) – Provides vehicle specific information for use in the consumption model. This information can include such things as the amount of energy consumed while travelling at a given speed. https://developer.here.com/documentation/routing/topics/resource-param-type-custom-consumption-details.html#type-standard

  • speed_profile (str) – Specifies the speed profile variant for a given routing mode. The speed profile affects travel time estimation as well as roads evaluation when computing the fastest route. Note that computed routes might differ depending on a used profile. https://developer.here.com/documentation/routing/topics/resource-param-type-speed-profile-type.html

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

  • dry_run – bool

Returns

raw JSON response

Return type

dict

matrix(locations: List[List[float]], profile: str, format: Optional[str] = 'json', mode_type: Optional[str] = 'fastest', sources: Optional[List[int]] = None, destinations: Optional[List[int]] = None, search_range: Optional[int] = None, avoid_areas: Optional[List[List[List[float]]]] = None, avoid_links: Optional[List[str]] = None, avoid_turns: Optional[str] = None, exclude_countries: Optional[List[str]] = None, departure: Optional[str] = None, matrix_attributes: Optional[List[str]] = None, summary_attributes: Optional[List[str]] = ['traveltime', 'costfactor', 'distance'], truck_type: Optional[str] = None, trailers_count: Optional[int] = None, shipped_hazardous_goods: Optional[List[str]] = None, limited_weight: Optional[int] = None, weight_per_axle: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, length: Optional[int] = None, tunnel_category: Optional[List[str]] = None, speed_profile: Optional[str] = None, dry_run: Optional[bool] = None, **matrix_kwargs)

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

Use matrix_kwargs for any missing matrix request options.

Parameters
Returns

raw JSON response

Return type

dict

MapboxOSRM

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

Performs requests to the OSRM API services.

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

Initializes a Mapbox OSRM client.

Parameters
directions(locations: List[List[float]], profile: str, radiuses: Optional[Union[List[float], Tuple[float]]] = None, bearings: Optional[List[List[int]]] = None, alternatives: Optional[bool] = None, steps: Optional[bool] = None, continue_straight: Optional[bool] = None, annotations: Optional[List[str]] = None, geometries: Optional[str] = None, overview: Optional[str] = None, exclude: Optional[str] = None, approaches: Optional[List[str]] = None, banner_instructions: Optional[bool] = None, language: Optional[str] = None, roundabout_exits: Optional[bool] = None, voice_instructions: Optional[bool] = None, voice_units: Optional[str] = None, waypoint_names: Optional[List[str]] = None, waypoint_targets: Optional[List[List[float]]] = None, dry_run: Optional[bool] = 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/#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: Optional[List[str]] = None, polygons: Optional[bool] = None, denoise: Optional[float] = None, generalize: Optional[float] = None, dry_run: Optional[bool] = None)

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

For more information, visit https://github.com/valhalla/valhalla/blob/master/docs/api/isochrone/api-reference.md.

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: Union[List[float], Tuple[float]], profile: str, sources: Optional[Union[List[int], Tuple[int]]] = None, destinations: Optional[Union[List[int], Tuple[int]]] = None, annotations: Optional[List[str]] = None, fallback_speed: Optional[int] = None, dry_run: Optional[bool] = 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

MapboxValhalla

OpenTripPlannerV2

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

Bases: object

Performs requests over OpenTripPlannerV2 GraphQL API.

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

Initializes an OpenTripPlannerV2 client.

Parameters
directions(locations: List[List[float]], profile: Optional[str] = 'WALK,TRANSIT', date: Optional[datetime.date] = datetime.date(2024, 1, 29), time: Optional[datetime.time] = datetime.time(9, 46, 10, 750345), arrive_by: Optional[bool] = False, num_itineraries: Optional[int] = 3, dry_run: Optional[bool] = 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: Optional[str] = 'WALK,TRANSIT', time: Optional[datetime.datetime] = datetime.datetime(2024, 1, 29, 9, 46, 10, 750396, tzinfo=datetime.timezone.utc), cutoffs: Optional[List[int]] = [3600], arrive_by: Optional[bool] = False, dry_run: Optional[bool] = 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: Optional[str] = 'WALK,TRANSIT', time: Optional[datetime.datetime] = datetime.datetime(2024, 1, 29, 9, 46, 10, 750422), cutoff: Optional[int] = 3600, arrive_by: Optional[bool] = False, dry_run: Optional[bool] = 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: typing.Optional[str] = None, base_url: typing.Optional[str] = 'https://api.openrouteservice.org', user_agent: typing.Optional[str] = None, timeout: typing.Optional[int] = DEFAULT, retry_timeout: typing.Optional[int] = None, retry_over_query_limit: typing.Optional[bool] = False, skip_api_error: typing.Optional[bool] = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the ORS API services.

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

Initializes an openrouteservice client.

Parameters
directions(locations: List[List[float]], profile: str, format: Optional[str] = 'geojson', preference: Optional[str] = None, alternative_routes: Optional[dict] = None, units: Optional[str] = None, language: Optional[str] = None, geometry: Optional[bool] = None, geometry_simplify: Optional[bool] = None, instructions: Optional[bool] = None, instructions_format: Optional[str] = None, roundabout_exits: Optional[bool] = None, attributes: Optional[List[str]] = None, radiuses: Optional[List[int]] = None, maneuvers: Optional[bool] = None, bearings: Optional[List[List[float]]] = None, continue_straight: Optional[bool] = None, elevation: Optional[bool] = None, extra_info: Optional[List[str]] = None, suppress_warnings: Optional[bool] = None, options: Optional[dict] = None, dry_run: Optional[bool] = 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”.

  • units (str) – Specifies the distance unit. One of [“m”, “km”, “mi”]. Default “m”.

  • 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: Optional[str] = 'time', units: Optional[str] = None, location_type: Optional[str] = 'start', smoothing: Optional[float] = None, attributes: Optional[List[str]] = None, intersections: Optional[bool] = None, dry_run: Optional[bool] = 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.

  • units (str) – Specifies the unit system to use when displaying results. One of [“m”, “km”, “m”]. Default “m”.

  • 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: Optional[List[int]] = None, destinations: Optional[List[int]] = None, metrics: Optional[List[str]] = None, resolve_locations: Optional[bool] = None, units: Optional[str] = None, dry_run: Optional[bool] = 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.

  • units (str) – Specifies the unit system to use when displaying results. One of [“m”, “km”, “m”]. Default “m”.

  • 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: typing.Optional[str] = 'https://routing.openstreetmap.de/routed-bike', user_agent: typing.Optional[str] = None, timeout: typing.Optional[int] = DEFAULT, retry_timeout: typing.Optional[int] = None, retry_over_query_limit: typing.Optional[bool] = False, skip_api_error: typing.Optional[bool] = None, client=<class 'routingpy.client_default.Client'>, **client_kwargs)

Performs requests to the OSRM API services.

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

Initializes an OSRM client.

Parameters
directions(locations: List[List[float]], profile: Optional[str] = 'driving', radiuses: Optional[List[int]] = None, bearings: Optional[List[List[float]]] = None, alternatives: Optional[Union[bool, int]] = None, steps: Optional[bool] = None, continue_straight: Optional[bool] = None, annotations: Optional[bool] = None, geometries: Optional[str] = None, overview: Optional[str] = None, dry_run: Optional[bool] = 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: Optional[str] = 'driving', radiuses: Optional[List[int]] = None, bearings: Optional[List[List[float]]] = None, sources: Optional[List[int]] = None, destinations: Optional[List[int]] = None, dry_run: Optional[bool] = None, annotations: Optional[List[str]] = ('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: typing.Optional[str] = None, timeout: typing.Optional[int] = DEFAULT, retry_timeout: typing.Optional[int] = None, retry_over_query_limit: typing.Optional[bool] = False, skip_api_error: typing.Optional[bool] = 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: typing.Optional[str] = None, timeout: typing.Optional[int] = DEFAULT, retry_timeout: typing.Optional[int] = None, retry_over_query_limit: typing.Optional[bool] = False, skip_api_error: typing.Optional[bool] = 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://github.com/valhalla/valhalla/blob/master/docs/api/turn-by-turn/api-reference.md#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: Optional[str] = None, options: Optional[dict] = None, units: Optional[str] = None, instructions: Optional[bool] = False, language: Optional[str] = None, directions_type: Optional[str] = None, avoid_locations: Optional[List[List[float]]] = None, avoid_polygons: Optional[List[List[List[float]]]] = None, date_time: Optional[dict] = None, id: Optional[Union[str, int, float]] = None, dry_run: Optional[bool] = None, **kwargs)

Get directions between an origin point and a destination point.

For more information, visit https://github.com/valhalla/valhalla/blob/master/docs/api/turn-by-turn/api-reference.md.

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://github.com/valhalla/valhalla/blob/master/docs/api/turn-by-turn/api-reference.md#costing-options

  • units – Distance units for output. One of [‘mi’, ‘km’]. Default km.

  • 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 from provided coordinates and restrictions.

Return type

routingpy.direction.Direction

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

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

For more information, visit https://valhalla.readthedocs.io/en/latest/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 “durations”, “distances”, “costs”, “edge_ids”, “statuses”. Note, that each additional property will increase the output size by minimum ~ 25%.

  • 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://github.com/valhalla/valhalla/blob/master/docs/api/turn-by-turn/api-reference.md#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 thru 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, units=None, instructions=False, language=None, directions_type=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().

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, units=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: Optional[str] = 'time', colors: Optional[List[str]] = None, polygons: Optional[bool] = None, denoise: Optional[float] = None, generalize: Optional[float] = None, preference: Optional[str] = None, options: Optional[dict] = None, units: Optional[str] = None, language: Optional[str] = None, directions_type: Optional[str] = None, avoid_locations: Optional[List[List[float]]] = None, avoid_polygons: Optional[List[List[List[float]]]] = None, date_time: Optional[dict] = None, show_locations: Optional[List[List[float]]] = None, id: Optional[str] = None, dry_run: Optional[bool] = None, **kwargs)

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

For more information, visit https://github.com/valhalla/valhalla/blob/master/docs/api/isochrone/api-reference.md.

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://github.com/valhalla/valhalla/blob/master/docs/api/turn-by-turn/api-reference.md#costing-options

  • units – Distance units for output. One of [‘mi’, ‘km’]. Default km.

  • 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 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.

    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: Optional[List[int]] = None, destinations: Optional[List[int]] = None, preference: Optional[str] = None, options: Optional[dict] = None, avoid_locations: Optional[List[List[float]]] = None, avoid_polygons: Optional[List[List[List[float]]]] = None, units: Optional[str] = None, date_time: Optional[dict] = None, id: Optional[str] = None, dry_run: Optional[bool] = None, **kwargs)

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

For more information, visit https://github.com/valhalla/valhalla/blob/master/docs/api/matrix/api-reference.md.

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://github.com/valhalla/valhalla/blob/master/docs/api/turn-by-turn/api-reference.md#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).

  • units – Distance units for output. One of [‘mi’, ‘km’]. Default km.

  • 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

trace_attributes(locations: Optional[Sequence[Union[Sequence[float], routingpy.routers.valhalla.Valhalla.Waypoint]]] = None, profile: str = 'bicycle', shape_match: str = 'walk_or_snap', encoded_polyline: Optional[str] = None, filters: Optional[List[str]] = None, filters_action: Optional[str] = None, options: Optional[dict] = None, dry_run: Optional[bool] = None, **kwargs) routingpy.valhalla_attributes.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://github.com/valhalla/valhalla/blob/master/docs/api/map-matching/api-reference.md#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://github.com/valhalla/valhalla/blob/master/docs/api/turn-by-turn/api-reference.md#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: Optional[dict]

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: Optional[List[List[float]]]

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

Return type

list or None

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: Optional[dict]

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: Optional[Union[List[float], Tuple[float]]]

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: Optional[List[List[float]]]

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: Optional[List[List[float]]]

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),
        ...
    ],
    ...
]
Return type

list or None

property durations: Optional[List[List[float]]]

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: Optional[dict]

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: Optional[List[routingpy.expansion.Edge]] = None, center: Optional[Union[List[float], Tuple[float]]] = None, interval_type: Optional[str] = None, raw: Optional[dict] = 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: Optional[Union[List[float], Tuple[float]]]

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: Optional[dict]
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, distances=None, durations=None, costs=None, edge_ids=None, statuses=None)

Contains a parsed single line string of an edge and its attributes, if specified in the request. Access via properties geometry, distances durations, costs, edge_ids, statuses.

property cost: Optional[int]

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

Return type

int or None

property distance: Optional[int]

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

Return type

int or None

property duration: Optional[int]

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

Return type

int or None

property edge_id: Optional[int]

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

Return type

int or None

property geometry: Optional[List[List[float]]]

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

Return type

list or None

property status: Optional[str]

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

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: routingpy.exceptions.RouterError

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

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

Bases: routingpy.exceptions.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: routingpy.exceptions.RouterError, routingpy.exceptions.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.