Create osrm.py
Browse files- services/osrm.py +33 -0
services/osrm.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
import requests
|
| 3 |
+
from typing import List, Tuple
|
| 4 |
+
|
| 5 |
+
OSRM = "https://router.project-osrm.org" # Public OSRM
|
| 6 |
+
|
| 7 |
+
def _profile_for(mode: str) -> str:
|
| 8 |
+
# OSRMの公開プロファイル名は driving / foot / bike
|
| 9 |
+
if mode == "foot":
|
| 10 |
+
return "foot"
|
| 11 |
+
if mode == "bike":
|
| 12 |
+
return "bike"
|
| 13 |
+
return "driving"
|
| 14 |
+
|
| 15 |
+
def route_polyline(coords: List[Tuple[float, float]], profile: str = "driving"):
|
| 16 |
+
locs = ";".join([f"{lon},{lat}" for lon, lat in coords])
|
| 17 |
+
url = f"{OSRM}/route/v1/{_profile_for(profile)}/{locs}"
|
| 18 |
+
params = {"overview": "full", "geometries": "geojson"}
|
| 19 |
+
r = requests.get(url, params=params, timeout=30)
|
| 20 |
+
r.raise_for_status()
|
| 21 |
+
j = r.json()
|
| 22 |
+
if not j.get("routes"):
|
| 23 |
+
return None
|
| 24 |
+
return j["routes"][0]
|
| 25 |
+
|
| 26 |
+
def distance_matrix(coords: List[Tuple[float, float]], profile: str = "driving"):
|
| 27 |
+
locs = ";".join([f"{lon},{lat}" for lon, lat in coords])
|
| 28 |
+
url = f"{OSRM}/table/v1/{_profile_for(profile)}/{locs}"
|
| 29 |
+
params = {"annotations": "duration,distance"}
|
| 30 |
+
r = requests.get(url, params=params, timeout=30)
|
| 31 |
+
r.raise_for_status()
|
| 32 |
+
j = r.json()
|
| 33 |
+
return j.get("durations"), j.get("distances")
|