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
Stack Overflow:https://stackoverflow.com/questions/tagged/routingpy
PyPI:https://pypi.org/project/routingpy
Conda:https://conda.org/gis-ops/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.5, 3.6, 3.7 and PyPy3.

Installation

pip install routingpy
# or
conda install routingpy

Routers

Every routing service below has a separate module in routingpy.routers, which hosts a class which bases routingpy.routers.base.Router astracting 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.

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:routingpy.routers.base.Router

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.headers)
{'User-Agent': 'amazing_routing_app', 'Content-Type': 'application/json'}
>>> print(router.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/v0.2.3'

Google

class routingpy.routers.Google(api_key, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs={}, retry_over_query_limit=True, skip_api_error=None)

Performs requests to the Google API services.

__init__(api_key, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs={}, retry_over_query_limit=True, skip_api_error=None)

Initializes a Google client.

Parameters:
  • 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.
  • requests_kwargs (dict) –

    Extra keyword arguments for the requests library, which among other things allow for proxy auth to be implemented. Note, that proxies can be set globally in routingpy.routers.options.default_proxies.

    Example:

    >>> from routingpy.routers import Google
    >>> router = Google(my_key, requests_kwargs={'proxies': {'https': '129.125.12.0'}})
    >>> print(router.proxies)
    {'https': '129.125.12.0'}
    
  • 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.
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, profile, alternatives=None, avoid=None, optimize=None, language=None, region=None, units=None, arrival_time=None, departure_time=None, traffic_model=None, transit_mode=None, transit_routing_preference=None, dry_run=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 – 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
  • 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 – 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()

Implement this method for the router’s isochrones endpoint or raise NotImplementedError

matrix(locations, profile, sources=None, destinations=None, avoid=None, language=None, region=None, units=None, arrival_time=None, departure_time=None, traffic_model=None, transit_mode=None, transit_routing_preference=None, dry_run=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=None, base_url='https://graphhopper.com/api/1', user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs={}, retry_over_query_limit=False, skip_api_error=None)

Performs requests to the Graphhopper API services.

__init__(api_key=None, base_url='https://graphhopper.com/api/1', user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs={}, retry_over_query_limit=False, skip_api_error=None)

Initializes an graphhopper client.

Parameters:
  • api_key (str) – GH API key. Required if https://graphhopper.com/api is used.
  • base_url (str) – The base URL for the request. Defaults to the ORS API server. Should not have a trailing slash.
  • 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.
  • requests_kwargs (dict) –

    Extra keyword arguments for the requests library, which among other things allow for proxy auth to be implemented. Note, that proxies can be set globally in routingpy.routers.options.default_proxies.

    Example:

    >>> from routingpy.routers import Graphhopper
    >>> router = Graphhopper(my_key, requests_kwargs={'proxies': {'https': '129.125.12.0'}})
    >>> print(router.proxies)
    {'https': '129.125.12.0'}
    
  • 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.
directions(locations, profile, format=None, optimize=None, instructions=None, locale=None, elevation=None, points_encoded=None, calc_points=None, debug=None, point_hint=None, details=None, ch_disable=None, weighting=None, heading=None, heading_penalty=None, pass_through=None, block_area=None, avoid=None, algorithm=None, round_trip_distance=None, round_trip_seed=None, alternative_route_max_paths=None, alternative_route_max_weight_factor=None, alternative_route_max_share_factor=None, dry_run=None)

Get directions between an origin point and a destination point.

For more information, visit https://docs.graphhopper.com/#tag/Routing-API/paths/~1route/get.

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_hint (bool) – Optional parameter. Specifies a hint for each point parameter to prefer a certain street for the closest location lookup. E.g. if there is an address or house with two or more neighboring streets you can control for which street the closest location is looked up.
  • details (list of str) – Optional parameter. Optional parameter to retrieve path details. You can request additional details for the route: street_name and time. For all motor vehicles we additionally support max_speed, toll (no, all, hgv), road_class (motorway, primary, …), road_environment, and surface. The returned format for one details is [fromRef, toRef, value]. The ref references the points of the response. Multiple details are possible via multiple key value pairs details=time&details=toll
  • ch_disable (bool) – Always use ch_disable=true in combination with one or more parameters of this table. Default False.
  • weighting (str) – Which kind of ‘best’ route calculation you need. Other options are shortest (e.g. for vehicle=foot or bike) and short_fastest if not only time but also distance is expensive. Default “fastest”.
  • heading (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.
  • block_area (str) – Optional parameter. Block road access via a point with the format latitude,longitude or an area defined by a circle lat,lon,radius or a rectangle lat1,lon1,lat2,lon2.
  • avoid (list of str) – Optional semicolon separated parameter. Specify which road classes you would like to avoid (currently only supported for motor vehicles like car). Possible values are ferry, motorway, toll, tunnel and ford.
  • 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 – 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, profile, intervals, buckets=1, interval_type=None, reverse_flow=None, debug=None, dry_run=None)

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

For mroe 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 bike, car, foot or https://graphhopper.com/api/1/docs/supported-vehicle-profiles/Default. 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.
  • 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, profile, sources=None, destinations=None, out_array=['times', 'distances'], debug=None, dry_run=None)

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

For more details visit https://docs.graphhopper.com/#tag/Matrix-API.

Parameters:
  • locations (list of list or tuple of tuple or list of tuple or tuple of list) – Specifiy 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. Cannot be used together with from_point or to_point. 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 of int) – The starting points for the routes. Specifies an index referring to locations.
  • destinations (list of int) – The destination points for the routes. Specifies an index referring to locations.
  • out_array (list of 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=None, app_code=None, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Performs requests to the HERE Maps API services.

__init__(app_id=None, app_code=None, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Initializes a HERE Maps client.

Parameters:
  • app_id (str) – HERE Maps app id.
  • app_code (str) – HERE Maps app code.
  • 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.
  • requests_kwargs (dict) –

    Extra keyword arguments for the requests library, which among other things allow for proxy auth to be implemented. Note, that proxies can be set globally in routingpy.routers.options.default_proxies.

    Example:

    >>> from routingpy.routers import HereMaps
    >>> router = HereMaps(my_api_id, my_api_code, requests_kwargs={'proxies': {'https': '129.125.12.0'}})
    >>> print(router.proxies)
    {'https': '129.125.12.0'}
    
  • 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.
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, profile, mode_type='fastest', format='json', request_id=None, avoid_areas=None, avoid_links=None, avoid_seasonal_closures=None, avoid_turns=None, allowed_zones=None, exclude_zones=None, exclude_zone_types=None, exclude_countries=None, arrival=None, departure=None, alternatives=None, metric_system=None, view_bounds=None, resolution=None, instruction_format=None, language=None, json_attributes=None, json_callback=None, representation=None, route_attributes=['waypoints', 'summary', 'shape', 'boundingBox', 'legs'], leg_attributes=None, maneuver_attributes=None, link_attributes=None, line_attributes=None, generalization_tolerances=None, vehicle_type=None, license_plate=None, max_number_of_changes=None, avoid_transport_types=None, walk_time_multiplier=None, walk_speed=None, walk_radius=None, combine_change=None, truck_type=None, trailers_count=None, shipped_hazardous_goods=None, limited_weight=None, weight_per_axle=None, height=None, width=None, length=None, tunnel_category=None, truck_restriction_penalty=None, return_elevation=None, consumption_model=None, custom_consumption_details=None, speed_profile=None, dry_run=None)

Get directions between an origin point and a destination point.

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 str) – 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 – 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 – 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 lastcharacter 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 – 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, profile, intervals, mode_type='fastest', interval_type='time', format='json', center_type='start', request_id=None, arrival=None, departure=None, single_component=None, resolution=None, max_points=None, quality=None, json_attributes=None, json_callback=None, truck_type=None, trailers_count=None, shipped_hazardous_goods=None, limited_weight=None, weight_per_axle=None, height=None, width=None, length=None, tunnel_category=None, consumption_model=None, custom_consumption_details=None, speed_profile=None, dry_run=None)

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

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 – 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 – 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 – 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 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:

raw JSON response

Return type:

dict

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

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

Parameters:
Returns:

raw JSON response

Return type:

dict

MapboxOSRM

class routingpy.routers.MapboxOSRM(api_key, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Performs requests to the OSRM API services.

__init__(api_key, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Initializes a Mapbox OSRM client.

Parameters:
  • api_key (str) – Mapbox 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.
  • requests_kwargs (dict) –

    Extra keyword arguments for the requests library, which among other things allow for proxy auth to be implemented. Note, that proxies can be set globally in routingpy.routers.options.default_proxies.

    Example:

    >>> from routingpy.routers import MapboxOSRM
    >>> router = MapboxOSRM(my_key, requests_kwargs={'proxies': {'https': '129.125.12.0'}})
    >>> print(router.proxies)
    {'https': '129.125.12.0'}
    
  • 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.
directions(locations, profile, radiuses=None, bearings=None, alternatives=None, steps=None, continue_straight=None, annotations=None, geometries=None, overview=None, exclude=None, approaches=None, banner_instructions=None, language=None, roundabout_exits=None, voice_instructions=None, voice_units=None, waypoint_names=None, waypoint_targets=None, dry_run=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, profile, intervals, contours_colors=None, polygons=None, denoise=None, generalize=None, dry_run=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 [“mapbox/driving”, “mapbox/walking”, “mapbox/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, profile, sources=None, destinations=None, annotations=None, fallback_speed=None, dry_run=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

class routingpy.routers.MapboxValhalla(api_key, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Bases: routingpy.routers.valhalla.Valhalla

Performs requests to Mapbox’s Valhalla instance.

__init__(api_key, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Initializes a Valhalla client.

Parameters:
  • api_key (str) – Mapbox 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.
  • requests_kwargs (dict) –

    Extra keyword arguments for the requests library, which among other things allow for proxy auth to be implemented. Note, that proxies can be set globally in routingpy.routers.options.default_proxies.

    Example:

    >>> from routingpy.routers import MapboxValhalla
    >>> router = MapboxValhalla(my_key, requests_kwargs={'proxies': {'https': '129.125.12.0'}})
    >>> print(router.proxies)
    {'https': '129.125.12.0'}
    
  • 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.
class Waypoint(position, type=None, heading=None, heading_tolerance=None, minimum_reachability=None, radius=None, rank_candidates=None)

Bases: object

Constructs a waypoint with additional information, such as via or encoded lines.

Example:

>>> waypoint = Valhalla.WayPoint(position=[8.15315, 52.53151], type='break', heading=120, heading_tolerance=10, minimum_reachability=10, radius=400)
>>> route = Valhalla('http://localhost/v1').directions(locations=[[[8.58232, 51.57234]], waypoint, [7.15315, 53.632415]])
directions(locations, profile, options=None, units=None, language=None, directions_type=None, avoid_locations=None, date_time=None, id=None, dry_run=None)

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.

Parameters:
  • locations (list of list or list of Valhalla.WayPoint) – 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 (str) – Specifies the mode of transport to use when calculating directions. One of [“auto”, “auto_shorter”, “bicycle”, “bus”, “hov”, “motor_scooter”, “motorcycle”, “multimodal”, “pedestrian”.
  • options (dict) – 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 (str) – Distance units for output. One of [‘mi’, ‘km’]. Default km.
  • language (str) – 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 (str) – ‘none’: no instructions are returned. ‘maneuvers’: only maneuvers are returned. ‘instructions’: maneuvers with instructions are returned. Default ‘instructions’.
  • avoid_locations (list of list or list of Valhalla.WayPoint) – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.
  • date_time (dict) – 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: 2019-03-03T08:06:23}
  • id (str) – 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.
  • dry_run – bool
Returns:

A route from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction

isochrones(locations, profile, intervals, colors=None, polygons=None, denoise=None, generalize=None, options=None, units=None, language=None, directions_type=None, avoid_locations=None, date_time=None, id=None, dry_run=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 [“auto”, “bicycle”, “multimodal”, “pedestrian”.
  • intervals (list of int) – Time ranges to calculate isochrones for. Up to 4 ranges are possible. In seconds.
  • 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.
  • options (dict) – 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 (str) – Distance units for output. One of [‘mi’, ‘km’]. Default km.
  • language (str) – 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 (list of list) – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.
  • date_time (dict) –

    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: 2019-03-03T08:06}

  • id (str) – 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.
  • dry_run – bool
Returns:

An isochrone with the specified range.

Return type:

routingpy.isochrone.Isochrones

matrix(locations, profile, sources=None, destinations=None, options=None, avoid_locations=None, units=None, id=None, dry_run=None)

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

Parameters:
  • locations (list of list) – Multiple pairs of lng/lat values.
  • profile (str) – Specifies the mode of transport to use when calculating matrices. One of [“auto”, “bicycle”, “multimodal”, “pedestrian”.
  • 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.
  • options (dict) – 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 (list of list) – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.
  • units (str) – Distance units for output. One of [‘mi’, ‘km’]. Default km.
  • id (str) – 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.
  • dry_run – bool
Returns:

A matrix from the specified sources and destinations.

Return type:

routingpy.matrix.Matrix

req

Holds the requests.PreparedRequest property for the last request.

ORS

class routingpy.routers.ORS(api_key=None, base_url='https://api.openrouteservice.org', user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Performs requests to the ORS API services.

__init__(api_key=None, base_url='https://api.openrouteservice.org', user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Initializes an openrouteservice client.

Parameters:
  • api_key (str) – ORS API key. Required if https://api.openrouteservice.org is used.
  • base_url (str) – The base URL for the request. Defaults to the ORS API server. Should not have a trailing slash.
  • 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.
  • requests_kwargs (dict) –

    Extra keyword arguments for the requests library, which among other things allow for proxy auth to be implemented. Note, that proxies can be set globally in routingpy.routers.options.default_proxies.

    Example:

    >>> from routingpy.routers import ORS
    >>> router = ORS(my_key, requests_kwargs={'proxies': {'https': '129.125.12.0'}})
    >>> print(router.proxies)
    {'https': '129.125.12.0'}
    
  • 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.
directions(locations, profile, format='geojson', preference=None, units=None, language=None, geometry=None, geometry_simplify=None, instructions=None, instructions_format=None, roundabout_exits=None, attributes=None, radiuses=None, maneuvers=None, bearings=None, continue_straight=None, elevation=None, extra_info=None, suppress_warnings=None, options=None, dry_run=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.
  • 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 – Specifies whether the maneuver object is included into the step object or not. Default: False.

:type maneuvers bool

Parameters:
  • 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/documentation for detailed documentation. Construct your own dict() options object and paste it to your code.
  • dry_run – Print URL and parameters without sending the request.
  • dry_run – bool
Returns:

A route from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction

isochrones(locations, profile, intervals, interval_type=None, units=None, location_type=None, smoothing=None, attributes=None, intersections=None, dry_run=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) – Write smth.
  • 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, profile, sources=None, destinations=None, metrics=None, resolve_locations=None, units=None, dry_run=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='https://router.project-osrm.org', user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Performs requests to the OSRM API services.

__init__(base_url='https://router.project-osrm.org', user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Initializes an OSRM client.

Parameters:
  • base_url (str) – The base URL for the request. Defaults to the OSRM demo API server. Should not have a trailing slash.
  • 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.
  • requests_kwargs (dict) –

    Extra keyword arguments for the requests library, which among other things allow for proxy auth to be implemented. Note, that proxies can be set globally in routingpy.routers.options.default_proxies.

    Example:

    >>> from routingpy.routers import OSRM
    >>> router = OSRM(requests_kwargs={'proxies': {'https': '129.125.12.0'}})
    >>> print(router.proxies)
    {'https': '129.125.12.0'}
    
  • 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.
directions(locations, profile, radiuses=None, bearings=None, alternatives=None, steps=None, continue_straight=None, annotations=None, geometries=None, overview=None, dry_run=None)

Get directions between an origin point and a destination point.

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

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 [“car”, “bike”, “foot”].
  • 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 uturns 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 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

isochrones()

Implement this method for the router’s isochrones endpoint or raise NotImplementedError

matrix(locations, profile, radiuses=None, bearings=None, sources=None, destinations=None, dry_run=None)

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

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) – Specifies the mode of transport to use when calculating directions. One of [“car”, “bike”, “foot”].
  • 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 – 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

Valhalla

class routingpy.routers.Valhalla(base_url, api_key=None, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Performs requests to a Valhalla instance.

__init__(base_url, api_key=None, user_agent=None, timeout=DEFAULT, retry_timeout=None, requests_kwargs=None, retry_over_query_limit=False, skip_api_error=None)

Initializes a Valhalla client.

Parameters:
  • api_key (str) – Mapbox API key. Required if base_url=’https://api.mapbox.com/valhalla/v1’.
  • base_url (str) – The base URL for the request. Defaults to the ORS API server. Should not have a trailing slash.
  • 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.
  • requests_kwargs (dict) –

    Extra keyword arguments for the requests library, which among other things allow for proxy auth to be implemented. Note, that proxies can be set globally in routingpy.routers.options.default_proxies.

    Example:

    >>> from routingpy.routers import Valhalla
    >>> router = Valhalla(my_key, requests_kwargs={'proxies': {'https': '129.125.12.0'}})
    >>> print(router.proxies)
    {'https': '129.125.12.0'}
    
  • 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.
class Waypoint(position, type=None, heading=None, heading_tolerance=None, minimum_reachability=None, radius=None, rank_candidates=None)

Constructs a waypoint with additional information, such as via or encoded lines.

Example:

>>> waypoint = Valhalla.WayPoint(position=[8.15315, 52.53151], type='break', heading=120, heading_tolerance=10, minimum_reachability=10, radius=400)
>>> route = Valhalla('http://localhost/v1').directions(locations=[[[8.58232, 51.57234]], waypoint, [7.15315, 53.632415]])
directions(locations, profile, options=None, units=None, language=None, directions_type=None, avoid_locations=None, date_time=None, id=None, dry_run=None)

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.

Parameters:
  • locations (list of list or list of Valhalla.WayPoint) – 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 (str) – Specifies the mode of transport to use when calculating directions. One of [“auto”, “auto_shorter”, “bicycle”, “bus”, “hov”, “motor_scooter”, “motorcycle”, “multimodal”, “pedestrian”.
  • options (dict) – 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 (str) – Distance units for output. One of [‘mi’, ‘km’]. Default km.
  • language (str) – 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 (str) – ‘none’: no instructions are returned. ‘maneuvers’: only maneuvers are returned. ‘instructions’: maneuvers with instructions are returned. Default ‘instructions’.
  • avoid_locations (list of list or list of Valhalla.WayPoint) – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.
  • date_time (dict) – 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: 2019-03-03T08:06:23}
  • id (str) – 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.
  • dry_run – bool
Returns:

A route from provided coordinates and restrictions.

Return type:

routingpy.direction.Direction

isochrones(locations, profile, intervals, colors=None, polygons=None, denoise=None, generalize=None, options=None, units=None, language=None, directions_type=None, avoid_locations=None, date_time=None, id=None, dry_run=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 [“auto”, “bicycle”, “multimodal”, “pedestrian”.
  • intervals (list of int) – Time ranges to calculate isochrones for. Up to 4 ranges are possible. In seconds.
  • 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.
  • options (dict) – 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 (str) – Distance units for output. One of [‘mi’, ‘km’]. Default km.
  • language (str) – 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 (list of list) – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.
  • date_time (dict) –

    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: 2019-03-03T08:06}

  • id (str) – 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.
  • dry_run – bool
Returns:

An isochrone with the specified range.

Return type:

routingpy.isochrone.Isochrones

matrix(locations, profile, sources=None, destinations=None, options=None, avoid_locations=None, units=None, id=None, dry_run=None)

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

Parameters:
  • locations (list of list) – Multiple pairs of lng/lat values.
  • profile (str) – Specifies the mode of transport to use when calculating matrices. One of [“auto”, “bicycle”, “multimodal”, “pedestrian”.
  • 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.
  • options (dict) – 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 (list of list) – A set of locations to exclude or avoid within a route. Specified as a list of coordinates, similar to coordinates object.
  • units (str) – Distance units for output. One of [‘mi’, ‘km’]. Default km.
  • id (str) – 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.
  • dry_run – bool
Returns:

A matrix from the specified sources and destinations.

Return type:

routingpy.matrix.Matrix

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.

raw

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.

distance

The distance of the entire trip in meters.

Return type:int
duration

The duration of the entire trip in seconds.

Return type:int
geometry

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.

raw

Returns the isochrones’s 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)

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

center

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
geometry

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.

distances

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
durations

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
raw

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

Return type:dict or None
routingpy.utils.decode_polyline5(polyline, is3d=False)

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.
Returns:

List of decoded coordinates with precision 5.

Return type:

list

routingpy.utils.decode_polyline6(polyline, is3d=False)

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