python-osrm

repository·master·Indexed 40 days ago

https://github.com/ustroetz/python-osrm

A Python wrapper for the Open Source Routing Machine (OSRM) API. It provides access to routing, matching, table, trip, and nearest services, including a Point class for coordinate management and an AccessIsochrone class for generating accessibility contours.

Tokens
1.7K
Snippets
9
Records
9
Agent score
0%

What's inside python-osrm

  1. Configure the OSRM host and profile using RequestConfig

    master

    You can change the target OSRM server or the profile (e.g., driving, biking) in two ways:

    1. Global Change: Modify osrm.RequestConfig.host to change the default URL for all subsequent requests.
    2. Instance-based Change: Create a new osrm.RequestConfig instance. This is useful for switching between different URLs or using basic authentication. Pass this instance to the url_config parameter of API functions.
    import osrm
    
    # Method 1: Change global default host
    osrm.RequestConfig.host = "router.project-osrm.org"
    
    # Method 2: Use a specific config instance for a single call
    # Supports basic authentication: basic_auth=("user", "pass")
    MyConfig = osrm.RequestConfig("localhost:9999/v1/biking", basic_auth=("user", "pass"))
    MyConfig.profile = "driving"
    
    # Use the config in a function call
    result = osrm.simple_route(p1, p2, url_config=MyConfig)
  2. Install python-osrm

    master

    Install the package using pip:

    $ pip install osrm

    Requirements

    Linux System Dependencies:

    • libgdal-dev

    Python Packages:

    • polyline
    • numpy
    • pandas
    • geopandas
    • GDAL
    pip install osrm
  3. Use osrm.nearest() to find the closest waypoint

    master

    The nearest function finds the closest point on the road network to the provided coordinate.

    import osrm
    
    res = osrm.nearest([22.1021271845936, 41.5078687005805])
    # Returns a dictionary containing 'waypoints' and 'code'
  4. Use osrm.match() to match coordinates to the road network

    master

    The match function takes a list of coordinates and matches them to the OSRM road network. You can specify whether to include steps and the level of geometry overview (e.g., simplified or full).

    import osrm
    
    points = [(-33.45017046193167,-70.65281867980957),
              (-33.45239047269638,-70.65300107002258),
              (-33.453867464504555,-70.65277576446533)]
    
    result = osrm.match(points, steps=False, overview="simplified")
  5. Generate accessibility isochrones with AccessIsochrone

    master

    The AccessIsochrone class uses the OSRM table service to draw accessibility contours around a point.

    Usage:

    1. Initialize AccessIsochrone with a center point and points_grid (precision/size of the grid).
    2. Use render_contour(n_class=...) to generate a GeoDataFrame of the contours.
    3. The grid of points used is also available via the .grid attribute as a GeoDataFrame.
    import osrm
    
    # Initialize with center (lat, lon) and grid precision
    Accessibility = osrm.AccessIsochrone((10.00, 53.55), points_grid=450)
    
    # Generate contour GeoDataFrame
    gdf = Accessibility.render_contour(n_class=8)
    
    # Plotting results
    gdf.plot(cmap="YlOrRd")
    Accessibility.grid.plot()
  6. Use osrm.trip() to solve the Traveling Salesperson Problem

    master

    The trip function fetches the optimal order of points to travel. You can specify output='only_index' to receive only the order of the points.

    import osrm
    
    coords = [(13.388860, 52.517037), (10.00, 53.55), (52.374444, 9.738611)]
    
    # Get only the order of points
    result = osrm.trip(coords, output="only_index")
  7. Use osrm.simple_route() to find a route between points

    master

    The simple_route function returns the original JSON response from the OSRM API. It supports decoding geometry into formats like WKT or WKB and allows you to filter the output to just the routes.

    Parameters:

    • output: Set to 'route' to only output the routes.
    • overview: Geometry overview level.
    • geometry: The format for decoded geometry (e.g., 'wkt', 'wkb').
    import osrm
    
    # Returns a list of routes with WKT geometry
    result = osrm.simple_route(
        [21.0566163803209, 42.004088575972], 
        [20.9574645547597, 41.5286973392856],
        output='route', 
        overview="full", 
        geometry='wkt'
    )
    
    print(result[0]['distance'])
    print(result[0]['geometry'])
  8. Use osrm.table() to fetch a distance/time matrix

    master

    The table function wraps the OSRM table service to return a matrix (as a pandas DataFrame or numpy array) and the snapped/corrected coordinates of the input points.

    Parameters:

    • ids_origin: Optional list of identifiers for the origin points to be used as column/row labels in the output.
    import osrm
    
    list_coord = [[21.0566163803209, 42.004088575972],
                  [21.3856064050746, 42.0094518118189],
                  [20.9574645547597, 41.5286973392856],
                  [21.1477394809847, 41.0691482795275],
                  [21.5506463080973, 41.3532256406286]]
    
    list_id = ['name1', 'name2', 'name3', 'name4', 'name5']
    
    time_matrix, snapped_coords = osrm.table(
        list_coord, 
        ids_origin=list_id, 
        output='dataframe'
    )
  9. Use the Point class to avoid coordinate confusion

    master

    To avoid confusion between x/y and latitude/longitude, use the osrm.Point class when passing coordinates to functions like simple_route.

    from osrm import Point, simple_route
    
    p1 = Point(latitude=2.386459, longitude=48.512369)
    p2 = Point(latitude=2.536974, longitude=48.793416)
    
    result = simple_route(p1, p2)