Skip to content

Commit 659d857

Browse files
authored
fix: remove unit conversion logic, add km and mi properties (#139)
In details: - removes the (erroneous) conversion logic as well as the `units` property on Valhalla and OpenRouteService `directions` functions, - adds two new properties to `Direction` class (`km` and `mi`). Fixes #138.
2 parents f749856 + 676d631 commit 659d857

File tree

7 files changed

+66
-86
lines changed

7 files changed

+66
-86
lines changed

routingpy/direction.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,14 @@ def distance(self) -> int:
114114
"""
115115
return self._distance
116116

117+
@property
118+
def km(self) -> float:
119+
return self.distance / 1000
120+
121+
@property
122+
def mi(self) -> float:
123+
return self.distance * 0.0006213712
124+
117125
@property
118126
def raw(self) -> Optional[dict]:
119127
"""

routingpy/routers/openrouteservice.py

Lines changed: 4 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,6 @@ def directions( # noqa: C901
106106
format: Optional[str] = "geojson",
107107
preference: Optional[str] = None,
108108
alternative_routes: Optional[dict] = None,
109-
units: Optional[str] = None,
110109
language: Optional[str] = None,
111110
geometry: Optional[bool] = None,
112111
geometry_simplify: Optional[bool] = None,
@@ -151,9 +150,6 @@ def directions( # noqa: C901
151150
and "weight_factor".
152151
:type alternative_routes: dict
153152
154-
:param units: Specifies the distance unit. One of ["m", "km", "mi"]. Default "m".
155-
:type units: str
156-
157153
:param language: Language for routing instructions. One of ["en", "de", "cn",
158154
"es", "ru", "dk", "fr", "it", "nl", "br", "se", "tr", "gr"].
159155
:type language: str
@@ -254,9 +250,6 @@ def directions( # noqa: C901
254250
)
255251
params["alternative_routes"] = alternative_routes
256252

257-
if units:
258-
params["units"] = units
259-
260253
if language:
261254
params["language"] = language
262255

@@ -315,21 +308,14 @@ def directions( # noqa: C901
315308
dry_run=dry_run,
316309
),
317310
format,
318-
units,
319311
alternative_routes,
320312
)
321313

322314
@staticmethod
323-
def parse_direction_json(response, format, units, alternative_routes):
315+
def parse_direction_json(response, format, alternative_routes):
324316
if response is None: # pragma: no cover
325317
return Direction()
326318

327-
units_factor = 1
328-
if units == "mi":
329-
units_factor = 0.621371 * 1000
330-
elif units == "km":
331-
units_factor = 1000
332-
333319
if format == "geojson":
334320
if alternative_routes:
335321
routes = []
@@ -346,9 +332,7 @@ def parse_direction_json(response, format, units, alternative_routes):
346332
else:
347333
geometry = response["features"][0]["geometry"]["coordinates"]
348334
duration = int(response["features"][0]["properties"]["summary"]["duration"])
349-
distance = int(
350-
response["features"][0]["properties"]["summary"]["distance"] * units_factor
351-
)
335+
distance = int(response["features"][0]["properties"]["summary"]["distance"])
352336
return Direction(geometry=geometry, duration=duration, distance=distance, raw=response)
353337
elif format == "json":
354338
if alternative_routes:
@@ -360,7 +344,7 @@ def parse_direction_json(response, format, units, alternative_routes):
360344
routes.append(
361345
Direction(
362346
geometry=geometry,
363-
distance=int(route["summary"]["distance"] * units_factor),
347+
distance=int(route["summary"]["distance"]),
364348
duration=int(route["summary"]["duration"]),
365349
raw=route,
366350
)
@@ -369,7 +353,7 @@ def parse_direction_json(response, format, units, alternative_routes):
369353
else:
370354
geometry = utils.decode_polyline5(response["routes"][0]["geometry"])
371355
duration = int(response["routes"][0]["summary"]["duration"])
372-
distance = int(response["routes"][0]["summary"]["distance"] * units_factor)
356+
distance = int(response["routes"][0]["summary"]["distance"])
373357

374358
return Direction(geometry=geometry, duration=duration, distance=distance, raw=response)
375359

@@ -379,7 +363,6 @@ def isochrones(
379363
profile: str,
380364
intervals: List[int],
381365
interval_type: Optional[str] = "time",
382-
units: Optional[str] = None,
383366
location_type: Optional[str] = "start",
384367
smoothing: Optional[float] = None,
385368
attributes: Optional[List[str]] = None,
@@ -405,10 +388,6 @@ def isochrones(
405388
a list of multiple ranges, e.g. [600, 1200, 1400]. In meters or seconds.
406389
:type intervals: list of int
407390
408-
:param units: Specifies the unit system to use when displaying results.
409-
One of ["m", "km", "m"]. Default "m".
410-
:type units: str
411-
412391
:param location_type: 'start' treats the location(s) as starting point,
413392
'destination' as goal. Default 'start'.
414393
:type location_type: str
@@ -441,9 +420,6 @@ def isochrones(
441420
if interval_type:
442421
params["range_type"] = interval_type
443422

444-
if units:
445-
params["units"] = units
446-
447423
if location_type:
448424
params["location_type"] = location_type
449425

@@ -492,7 +468,6 @@ def matrix(
492468
destinations: Optional[List[int]] = None,
493469
metrics: Optional[List[str]] = None,
494470
resolve_locations: Optional[bool] = None,
495-
units: Optional[str] = None,
496471
dry_run: Optional[bool] = None,
497472
):
498473
"""Gets travel distance and time for a matrix of origins and destinations.
@@ -524,10 +499,6 @@ def matrix(
524499
Default False.
525500
:type resolve_locations: bool
526501
527-
:param units: Specifies the unit system to use when displaying results.
528-
One of ["m", "km", "m"]. Default "m".
529-
:type units: str
530-
531502
:param dry_run: Print URL and parameters without sending the request.
532503
:param dry_run: bool
533504
@@ -549,9 +520,6 @@ def matrix(
549520
if resolve_locations is not None:
550521
params["resolve_locations"] = resolve_locations
551522

552-
if units:
553-
params["units"] = units
554-
555523
return self.parse_matrix_json(
556524
self.client._request(
557525
"/v2/matrix/" + profile + "/json", get_params={}, post_params=params, dry_run=dry_run

routingpy/routers/valhalla.py

Lines changed: 8 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,6 @@ def directions(
115115
profile: str,
116116
preference: Optional[str] = None,
117117
options: Optional[dict] = None,
118-
units: Optional[str] = None,
119118
instructions: Optional[bool] = False,
120119
language: Optional[str] = None,
121120
directions_type: Optional[str] = None,
@@ -149,8 +148,6 @@ def directions(
149148
will be filled automatically. For more information, visit:
150149
https://github.com/valhalla/valhalla/blob/master/docs/api/turn-by-turn/api-reference.md#costing-options
151150
152-
:param units: Distance units for output. One of ['mi', 'km']. Default km.
153-
154151
:param instructions: Whether to return turn-by-turn instructions. Named for compatibility with other
155152
providers. Valhalla's parameter here is 'narrative'.
156153
@@ -189,7 +186,6 @@ def directions(
189186
profile,
190187
preference,
191188
options,
192-
units,
193189
instructions,
194190
language,
195191
directions_type,
@@ -201,8 +197,7 @@ def directions(
201197
)
202198

203199
return self.parse_direction_json(
204-
self.client._request("/route", post_params=params, dry_run=dry_run),
205-
units,
200+
self.client._request("/route", post_params=params, dry_run=dry_run)
206201
)
207202

208203
@staticmethod
@@ -211,7 +206,6 @@ def get_direction_params(
211206
profile,
212207
preference=None,
213208
options=None,
214-
units=None,
215209
instructions=False,
216210
language=None,
217211
directions_type=None,
@@ -238,10 +232,8 @@ def get_direction_params(
238232
if preference == "shortest":
239233
params["costing_options"][profile]["shortest"] = True
240234

241-
if any((units, language, directions_type)):
235+
if any((language, directions_type)):
242236
params["directions_options"] = dict()
243-
if units:
244-
params["directions_options"]["units"] = units
245237
if language:
246238
params["directions_options"]["language"] = language
247239
if directions_type:
@@ -265,17 +257,17 @@ def get_direction_params(
265257
return params
266258

267259
@staticmethod
268-
def parse_direction_json(response, units):
260+
def parse_direction_json(response):
269261
if response is None: # pragma: no cover
270262
return Direction()
271263

272264
geometry, duration, distance = [], 0, 0
273265
for leg in response["trip"]["legs"]:
274266
geometry.extend(utils.decode_polyline6(leg["shape"]))
275267
duration += leg["summary"]["time"]
268+
distance += leg["summary"]["length"]
276269

277-
factor = 0.621371 if units == "mi" else 1
278-
distance += int(leg["summary"]["length"] * 1000 * factor)
270+
distance *= 1000 # convert to meters
279271

280272
return Direction(geometry=geometry, duration=int(duration), distance=int(distance), raw=response)
281273

@@ -504,7 +496,6 @@ def matrix(
504496
options: Optional[dict] = None,
505497
avoid_locations: Optional[List[List[float]]] = None,
506498
avoid_polygons: Optional[List[List[List[float]]]] = None,
507-
units: Optional[str] = None,
508499
date_time: Optional[dict] = None,
509500
id: Optional[str] = None,
510501
dry_run: Optional[bool] = None,
@@ -546,8 +537,6 @@ def matrix(
546537
efficient to use avoid_locations. Valhalla will close open rings (i.e. copy the first coordingate to the
547538
last position).
548539
549-
:param units: Distance units for output. One of ['mi', 'km']. Default km.
550-
551540
:param date_time: This is the local date and time at the location. Field ``type``: 0: Current departure time,
552541
1: Specified departure time. Field ``value```: the date and time is specified
553542
in format YYYY-MM-DDThh:mm, local time.
@@ -569,15 +558,13 @@ def matrix(
569558
options,
570559
avoid_locations,
571560
avoid_polygons,
572-
units,
573561
date_time,
574562
id,
575563
**kwargs
576564
)
577565

578566
return self.parse_matrix_json(
579-
self.client._request("/sources_to_targets", post_params=params, dry_run=dry_run),
580-
units,
567+
self.client._request("/sources_to_targets", post_params=params, dry_run=dry_run)
581568
)
582569

583570
@staticmethod
@@ -590,7 +577,6 @@ def get_matrix_params(
590577
options=None,
591578
avoid_locations=None,
592579
avoid_polygons=None,
593-
units=None,
594580
date_time=None,
595581
id=None,
596582
**kwargs
@@ -634,9 +620,6 @@ def get_matrix_params(
634620
if avoid_polygons:
635621
params["avoid_polygons"] = avoid_polygons
636622

637-
if units:
638-
params["units"] = units
639-
640623
if date_time:
641624
params["date_time"] = date_time
642625

@@ -648,19 +631,16 @@ def get_matrix_params(
648631
return params
649632

650633
@staticmethod
651-
def parse_matrix_json(response, units):
634+
def parse_matrix_json(response):
652635
if response is None: # pragma: no cover
653636
return Matrix()
654637

655-
factor = 0.621371 if units == "mi" else 1
656638
durations = [
657639
[destination["time"] for destination in origin] for origin in response["sources_to_targets"]
658640
]
659641
distances = [
660642
[
661-
int(destination["distance"] * 1000 * factor)
662-
if destination["distance"] is not None
663-
else None
643+
destination["distance"] * 1000 if destination["distance"] is not None else None
664644
for destination in origin
665645
]
666646
for origin in response["sources_to_targets"]

0 commit comments

Comments
 (0)