-
Notifications
You must be signed in to change notification settings - Fork 25
/
heremaps.py
1458 lines (1175 loc) 路 63.9 KB
/
heremaps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright (C) 2021 GIS OPS UG
#
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
#
from operator import itemgetter
from typing import List, Optional, Tuple, Union
from .. import convert
from ..client_base import DEFAULT
from ..client_default import Client
from ..direction import Direction, Directions
from ..isochrone import Isochrone, Isochrones
from ..matrix import Matrix
from ..utils import logger
class HereMaps:
"""Performs requests to the HERE Maps API services."""
def __init__(
self,
app_id: Optional[str] = None,
app_code: Optional[str] = None,
user_agent: Optional[str] = None,
timeout: Optional[int] = DEFAULT,
retry_timeout: Optional[int] = None,
retry_over_query_limit: Optional[bool] = False,
skip_api_error: Optional[bool] = None,
api_key: Optional[str] = None,
client=Client,
**client_kwargs
):
"""
Initializes a HERE Maps client.
:param app_id: HERE Maps app id.
:type app_id: str
:param app_code: HERE Maps app code.
:type app_code: str
:param user_agent: User Agent to be used when requesting.
Default :attr:`routingpy.routers.options.default_user_agent`.
:type user_agent: str
:param timeout: Combined connect and read timeout for HTTP requests, in
seconds. Specify ``None`` for no timeout. Default :attr:`routingpy.routers.options.default_timeout`.
:type timeout: int or None
:param retry_timeout: Timeout across multiple retriable requests, in
seconds. Default :attr:`routingpy.routers.options.default_retry_timeout`.
:type retry_timeout: int
:param 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.
Default :attr:`routingpy.routers.options.default_retry_over_query_limit`.
:type retry_over_query_limit: bool
:param skip_api_error: Continue with batch processing if a :class:`routingpy.exceptions.RouterApiError` is
encountered (e.g. no route found). If False, processing will discontinue and raise an error.
Default :attr:`routingpy.routers.options.default_skip_api_error`.
:type skip_api_error: bool
:param client: A client class for request handling. Needs to be derived from :class:`routingpy.client_base.BaseClient`
:type client: abc.ABCMeta
:param client_kwargs: Additional arguments passed to the client, such as headers or proxies.
:type client_kwargs: dict
"""
if app_id is None and app_code is None and api_key is None:
raise KeyError("HERE Maps app_id and app_code, or api_key must be specified.")
if (app_id is not None or app_code is not None) and api_key is not None:
raise KeyError(
"Either HERE Maps app_id and app_code, or api_key can be specified, not both."
)
self.app_code = app_code
self.app_id = app_id
self.api_key = api_key
if self.api_key:
self.auth = {"apikey": self.api_key}
else:
self.auth = {"app_id": self.app_id, "app_code": self.app_code}
self.client = client(
"",
user_agent,
timeout,
retry_timeout,
retry_over_query_limit,
skip_api_error,
**client_kwargs
)
class Waypoint(object):
"""
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]])
"""
def __init__(
self,
position,
waypoint_type=None,
stopover_duration=None,
transit_radius="",
user_label="",
heading="",
):
"""
:param position: Indicates that the parameter contains a geographical position.
:type position: list
:param waypoint_type: 180 degree turns are allowed for ``stopOver`` but not for ``passThrough``.
Waypoints defined through a drag-n-drop action should be marked as passThrough.
PassThrough waypoints will not appear in the list of maneuvers.
:type waypoint_type: str
:param stopover_duration: Stopover delay in seconds.
Impacts time-aware calculations. Ignored for passThrough.
:type stopover_duration: int
:param transit_radius: Matching Links are selected within the
specified TransitRadius, in meters.
For example to drive past a city without necessarily going into the
city center you can specify the coordinates of the center and a
TransitRadius of 5000m.
:type transit_radius: int
:param user_label: Custom label identifying this waypoint.
:type user_label: str
:param heading: Heading in degrees starting at true north and continuing
clockwise around the compass.
North is 0 degrees, East is 90 degrees, South is 180 degrees,
and West is 270 degrees.
:type heading: int
"""
self.position = position
self.waypoint_type = waypoint_type
self.stopover_duration = stopover_duration
self.transit_radius = str(transit_radius)
self.user_label = user_label
self.heading = str(heading)
def _make_waypoint(self):
here_waypoint = ["geo"]
if self.waypoint_type is not None and self.stopover_duration is not None:
here_waypoint.append(
convert.delimit_list([self.waypoint_type, self.stopover_duration], ",")
)
elif self.waypoint_type is not None:
here_waypoint.append(self.waypoint_type)
position = convert.delimit_list(
[convert.format_float(f) for f in list(reversed(self.position))], ","
)
position += ";" + self.transit_radius
position += ";" + self.user_label
position += ";" + self.heading
here_waypoint.append(position)
return convert.delimit_list(here_waypoint, "!")
class RoutingMode(object):
"""
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)
"""
def __init__(
self, mode_type="fastest", mode_transport_type="car", mode_traffic=None, features=None
):
"""
:param mode_type: RoutingType relevant to calculation.
:type mode_type: str
:param mode_transport_type: Specify which mode of transport to calculate the route for.
:type mode_transport_type: str
:param mode_traffic: Specify whether to optimize a route for traffic.
:type mode_traffic: bool
:param features: Route feature weightings to be applied when calculating
the route. As many as required.
:type features: dict
"""
self.mode_type = mode_type
self.mode_transport_type = mode_transport_type
self.mode_traffic = mode_traffic
self.features = features
def make_routing_mode(self):
routing_mode = []
routing_mode.append(self.mode_type)
routing_mode.append(self.mode_transport_type)
if self.mode_traffic is not None:
routing_mode.append("traffic:" + self.mode_traffic)
if self.features is not None:
get_features = []
for f, w in self.features.items():
get_features.append(convert.delimit_list([f, str(w)], ":"))
routing_mode.append(convert.delimit_list(get_features, ","))
return convert.delimit_list(routing_mode, ";")
def directions( # noqa: C901
self,
locations: List[List[float]],
profile: str,
mode_type: Optional[str] = "fastest",
format: Optional[str] = "json",
request_id: Optional[str] = None,
avoid_areas: Optional[List[List[List[float]]]] = None,
avoid_links: Optional[List[str]] = None,
avoid_seasonal_closures: Optional[bool] = None,
avoid_turns: Optional[str] = None,
allowed_zones: Optional[List[int]] = None,
exclude_zones: Optional[List[int]] = None,
exclude_zone_types: Optional[List[str]] = None,
exclude_countries: Optional[List[str]] = None,
arrival: Optional[str] = None,
departure: Optional[str] = None,
alternatives: Optional[int] = None,
metric_system: Optional[str] = None,
view_bounds: Optional[Union[List[float], Tuple[float]]] = None,
resolution: Optional[dict] = None,
instruction_format: Optional[str] = None,
language: Optional[str] = None,
json_attributes: Optional[int] = None,
json_callback: Optional[str] = None,
representation: Optional[List[str]] = None,
route_attributes: Optional[List[str]] = ["waypoints", "summary", "shape", "boundingBox", "legs"],
leg_attributes: Optional[List[str]] = None,
maneuver_attributes: Optional[List[str]] = None,
link_attributes: Optional[List[str]] = None,
line_attributes: Optional[List[str]] = None,
generalization_tolerances: Optional[List[float]] = None,
vehicle_type: Optional[str] = None,
license_plate: Optional[str] = None,
max_number_of_changes: Optional[int] = None,
avoid_transport_types: Optional[List[str]] = None,
walk_time_multiplier: Optional[float] = None,
walk_speed: Optional[float] = None,
walk_radius: Optional[int] = None,
combine_change: Optional[bool] = None,
truck_type: Optional[str] = None,
trailers_count: Optional[int] = None,
shipped_hazardous_goods: Optional[List[str]] = None,
limited_weight: Optional[int] = None,
weight_per_axle: Optional[int] = None,
height: Optional[int] = None,
width: Optional[int] = None,
length: Optional[int] = None,
tunnel_category: Optional[List[str]] = None,
truck_restriction_penalty: Optional[str] = None,
return_elevation: Optional[bool] = None,
consumption_model: Optional[str] = None,
custom_consumption_details: Optional[str] = None,
speed_profile: Optional[str] = None,
dry_run: Optional[bool] = None,
**directions_kwargs
):
"""Get directions between an origin point and a destination point.
Use ``direction_kwargs`` for any missing ``directions`` request options.
For more information, https://developer.here.com/documentation/routing/topics/resource-calculate-route.html.
:param locations: The coordinates tuple the route should be calculated
from in order of visit. Can be a list/tuple of [lon, lat] or :class:`HereMaps.Waypoint` instance or a
combination of those. For further explanation, see
https://developer.here.com/documentation/routing/topics/resource-param-type-waypoint.html
:type locations: list of list or list of :class:`HereMaps.Waypoint`
:param profile: Specifies the routing mode of transport and further options.
Can be a str and one of [car, pedestrian, carHOV, publicTransport, publicTransportTimeTable, truck, bicycle]
or :class:`HereMaps.RoutingMode`.
https://developer.here.com/documentation/routing/topics/resource-param-type-routing-mode.html
:type profile: str or :class:`HereMaps.RoutingMode`
:param mode_type: 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
:type mode_type: str
:param format: Currently only "json" supported.
:type format: str
:param request_id: 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.
:type request_id: str
:param avoid_areas: 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
:type avoid_areas: list of list of list
:param avoid_links: Links which the route must not cross. The list of LinkIdTypes.
:type avoid_links: list of str
:param avoid_seasonal_closures: 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).
:type avoid_seasonal_closures: bool
:param avoid_turns: List of turn types that the route should avoid.
Defaults to empty list.
https://developer.here.com/documentation/routing/topics/resource-type-enumerations.html
:type avoid_turns: str
:param allowed_zones: 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
:type allowed_zones: list of int
:param exclude_zones: Identifiers of zones which the route must not cross
under any circumstances.
https://developer.here.com/documentation/routing/topics/resource-get-routing-zones.html
:type exclude_zones: list of int
:param exclude_zone_types: 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
:type exclude_zone_types: list of str
:param exclude_countries: Countries that must be excluded from route calculation.
:type exclude_countries: list of str
:param departure: 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.
:type departure: str
:param arrival: 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.
:type arrival: str
:param alternatives: 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.
:type alternatives: int
:param metric_system: 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.
:type metric_system: str
:param view_bounds: 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.
:type view_bounds: list or tuple
:param resolution: 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}
:type resolution: dict
:param instruction_format: Defines the representation format of the maneuver's instruction text. Html or txt.
:type instruction_format: str
:param language: 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
:type language: str
:param json_attributes: Flag to control JSON output. Combine parameters
by adding their values.
https://developer.here.com/documentation/routing/topics/resource-param-type-json-representation.html
:type json_attributes: int
:param json_callback: Name of a user-defined function used to wrap the JSON response.
:type json_callback: str
:param representation: 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
:type representation: list of str
:param route_attributes: 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
:type route_attributes: list of str
:param leg_attributes: 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
:type leg_attributes: list of str
:param maneuver_attributes: 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
:type maneuver_attributes: list of str
:param link_attributes: 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
:type link_attributes: list of str
:param line_attributes: 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
:type line_attributes: list of str
:param generalization_tolerances: 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.
:type generalization_tolerances: list of float
:param param vehicle_type: 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
:type vehicle_type: str
:param param license_plate: Specifies fragments of vehicle's license plate number.
The last character is currently the only supported fragment type.
The license plate parameter enables evaluation of license plate
based vehicle restrictions like odd/even scheme in Indonesia.
:type license_plate: str
:param max_number_of_changes: 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.
:type max_number_of_changes: int
:param avoid_transport_types: 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
:type avoid_transport_types: list of str
:param walk_time_multiplier: 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.
:type walk_time_multiplier: float
:param walk_speed: 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.
:type walk_speed: float
:param walk_radius: 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.
:type walk_radius: int
:param combine_change: 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.
:type combine_change: bool
:param truck_type: Truck routing only, specifies the vehicle type. Defaults to truck.
:type truck_type: str
:param trailers_count: Truck routing only, specifies number of trailers
pulled by a vehicle. The provided value must be between 0 and 4.
Defaults to 0.
:type trailers_count: int
:param shipped_hazardous_goods: 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
:type shipped_hazardous_goods: list of str
:param limited_weight: Truck routing only, vehicle weight including
trailers and shipped goods, in tons. The provided value must be between 0 and 1000.
:type limited_weight: int
:param weight_per_axle: Truck routing only, vehicle weight per axle in
tons. The provided value must be between 0 and 1000.
:type weight_per_axle: int
:param height: Truck routing only, vehicle height in meters.
The provided value must be between 0 and 50.
:type height: int
:param width: Truck routing only, vehicle width in meters.
The provided value must be between 0 and 50.
:type width: int
:param length: Truck routing only, vehicle length in meters.
The provided value must be between 0 and 300.
:type length: int
:param tunnel_category: Truck routing only, specifies the tunnel category
to restrict certain route links. The route will pass only through tunnels
of a less strict category.
:type tunnel_category: list of str
:param truck_restriction_penalty: 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
:type truck_restriction_penalty: str
:param return_elevation: 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.
:type return_elevation: bool
:param consumption_model: 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
:type consumption_model: str
:param custom_consumption_details: 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
:type custom_consumption_details: str
:param speed_profile: 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
:type speed_profile: str
:param dry_run: Print URL and parameters without sending the request.
:param dry_run: bool
:returns: One or multiple route(s) from provided coordinates and restrictions.
:rtype: :class:`routingpy.direction.Direction` or :class:`routingpy.direction.Directions`
"""
self.client.base_url = (
"https://route.api.here.com/routing/7.2"
if self.api_key is None
else "https://route.ls.hereapi.com/routing/7.2"
)
params = self.auth.copy()
locations = self._build_locations(locations)
for idx, wp in enumerate(locations):
wp_index = "waypoint" + str(idx)
params[wp_index] = wp
if isinstance(profile, str):
params["mode"] = mode_type + ";" + profile
elif isinstance(profile, self.RoutingMode):
params["mode"] = profile.make_routing_mode()
if request_id is not None:
params["requestId"] = request_id
if avoid_areas is not None:
params["avoidAreas"] = convert.delimit_list(
[
convert.delimit_list(
[
convert.delimit_list(
[convert.format_float(f) for f in list(reversed(pair))], ","
)
for pair in bounding_box
],
";",
)
for bounding_box in avoid_areas
],
"!",
)
if avoid_links is not None:
params["avoidLinks"] = convert.delimit_list(avoid_links, ",")
if avoid_seasonal_closures is not None:
params["avoidSeasonalClosures"] = convert.convert_bool(avoid_seasonal_closures)
if avoid_turns is not None:
params["avoidTurns"] = avoid_turns
if allowed_zones is not None:
params["allowedZones"] = convert.delimit_list(allowed_zones, ",")
if exclude_zones is not None:
params["excludeZones"] = convert.delimit_list(exclude_zones, ",")
if exclude_zone_types is not None:
params["excludeZoneTypes"] = convert.delimit_list(exclude_zone_types, ",")
if exclude_countries is not None:
params["excludeCountries"] = convert.delimit_list(exclude_countries, ",")
if departure is not None:
params["departure"] = departure
elif arrival is not None:
params["arrival"] = arrival
if alternatives is not None:
params["alternatives"] = alternatives
if metric_system is not None:
params["metricSystem"] = metric_system
if view_bounds is not None:
params["viewBounds"] = convert.delimit_list(
[
convert.delimit_list([convert.format_float(f) for f in list(reversed(pair))], ",")
for pair in view_bounds
],
";",
)
if resolution is not None:
params["resolution"] = str(resolution["viewresolution"])
if "snapresolution" in resolution:
params["resolution"] += ":" + str(resolution["snapresolution"])
if instruction_format is not None:
params["instructionFormat"] = instruction_format
if json_attributes is not None:
params["jsonAttributes"] = json_attributes
if json_callback is not None:
params["jsonCallback"] = json_callback
if representation is not None:
params["representation"] = convert.delimit_list(representation, ",")
if route_attributes is not None:
params["routeAttributes"] = convert.delimit_list(route_attributes, ",")
if leg_attributes is not None:
params["legAttributes"] = convert.delimit_list(leg_attributes, ",")
if maneuver_attributes is not None:
params["maneuverAttributes"] = convert.delimit_list(maneuver_attributes, ",")
if link_attributes is not None:
params["linkAttributes"] = convert.delimit_list(link_attributes, ",")
if line_attributes is not None:
params["lineAttributes"] = convert.delimit_list(line_attributes, ",")
if generalization_tolerances is not None:
params["generalizationTolerances"] = convert.delimit_list(generalization_tolerances, ",")
if vehicle_type is not None:
params["vehicleType"] = vehicle_type
if license_plate is not None:
params["licensePlate"] = license_plate
if max_number_of_changes is not None:
params["maxNumberOfChanges"] = max_number_of_changes
if avoid_transport_types is not None:
params["avoidTransportTypes"] = convert.delimit_list(avoid_transport_types, ",")
if walk_time_multiplier is not None:
params["walkTimeMultiplier"] = walk_time_multiplier
if walk_speed is not None:
params["walkSpeed"] = walk_speed
if walk_radius is not None:
params["walkRadius"] = walk_radius
if combine_change is not None:
params["combineChange"] = convert.convert_bool(combine_change)
if truck_type is not None:
params["truckType"] = truck_type
if trailers_count is not None:
params["trailersCount"] = trailers_count
if shipped_hazardous_goods is not None:
params["shippedHazardousGoods"] = convert.delimit_list(shipped_hazardous_goods, ",")
if limited_weight is not None:
params["limitedWeight"] = limited_weight
if weight_per_axle is not None:
params["weightPerAxle"] = weight_per_axle
if height is not None:
params["height"] = height
if width is not None:
params["width"] = width
if length is not None:
params["length"] = length
if tunnel_category is not None:
params["tunnelCategory"] = convert.delimit_list(tunnel_category, ",")
if truck_restriction_penalty is not None:
params["truckRestrictionPenalty"] = truck_restriction_penalty
if return_elevation is not None:
params["returnElevation"] = convert.convert_bool(return_elevation)
if consumption_model is not None:
params["consumptionModel"] = consumption_model
if custom_consumption_details is not None:
params["customConsumptionDetails"] = custom_consumption_details
if speed_profile is not None:
params["speedProfile"] = speed_profile
params.update(directions_kwargs)
return self.parse_direction_json(
self.client._request(
convert.delimit_list(["/calculateroute", format], "."),
get_params=params,
dry_run=dry_run,
),
alternatives=alternatives,
)
@staticmethod
def parse_direction_json(response, alternatives):
if response is None: # pragma: no cover
if alternatives:
return Directions()
else:
return Direction()
if alternatives is not None and alternatives > 1:
routes = []
for route in response["response"]["route"]:
routes.append(
Direction(
geometry=[
list(reversed(list((map(float, coordinates.split(","))))))
for coordinates in route["shape"]
],
duration=int(route["summary"]["baseTime"]),
distance=int(route["summary"]["distance"]),
raw=route,
)
)
return Directions(directions=routes, raw=response)
else:
geometry = [
list(reversed(list(map(float, coordinates.split(",")))))
for coordinates in response["response"]["route"][0].get("shape")
]
duration = int(response["response"]["route"][0]["summary"].get("baseTime"))
distance = int(response["response"]["route"][0]["summary"].get("distance"))
return Direction(geometry=geometry, duration=duration, distance=distance, raw=response)
def isochrones( # noqa: C901
self,
locations: List[float],
profile: str,
intervals: List[int],
mode_type: Optional[str] = "fastest",
interval_type: Optional[str] = "time",
format: Optional[str] = "json",
center_type: Optional[str] = "start",
request_id: Optional[str] = None,
arrival: Optional[str] = None,
departure: Optional[str] = None,
single_component: Optional[bool] = None,
resolution: Optional[int] = None,
max_points: Optional[int] = None,
quality: Optional[int] = None,
json_attributes: Optional[int] = None,
json_callback=None,
truck_type: Optional[str] = None,
trailers_count: Optional[int] = None,
shipped_hazardous_goods: Optional[List[str]] = None,
limited_weight: Optional[int] = None,
weight_per_axle: Optional[int] = None,
height: Optional[int] = None,
width: Optional[int] = None,
length: Optional[int] = None,
tunnel_category: Optional[List[str]] = None,
consumption_model: Optional[str] = None,
custom_consumption_details: Optional[str] = None,
speed_profile: Optional[str] = None,
dry_run: Optional[bool] = None,
**isochrones_kwargs
):
"""Gets isochrones or equidistants for a range of time/distance values around a given set of coordinates.
Use ``isochrones_kwargs`` for any missing ``isochrones`` request options.
For more information, https://developer.here.com/documentation/routing/topics/resource-calculate-isoline.html.
:param locations: One pair of lng/lat values.
:type locations: list of float
:param profile: Specifies the routing mode of transport and further options.
Can be a str or :class:`HereMaps.RoutingMode`
https://developer.here.com/documentation/routing/topics/resource-param-type-routing-mode.html
:type profile: str or :class:`HereMaps.RoutingMode`
:param intervals: Range of isoline. Several comma separated values can be specified.
The unit is defined by parameter rangetype.
:type intervals: list of int
:param mode_type: 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
:type mode_type: str
:param 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
:type interval_type: str
:param format: Currently only "json" supported.
:type format: str
:param center_type: 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.
:type center_type: str
:param departure: 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.
:type departure: str
:param arrival: 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.
:type arrival: str
:param single_component: 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.
:type single_component: bool
:param resolution: 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.
:type resolution: int
:param max_points: 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.
:type max_points: int
:param quality: 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.
:type quality: int
:param json_attributes: Flag to control JSON output.
Combine parameters by adding their values.
https://developer.here.com/documentation/routing/topics/resource-param-type-json-representation.html
:type json_attributes: int
:param truck_type: Truck routing only, specifies the vehicle type. Defaults to truck.
:type truck_type: str
:param trailers_count: Truck routing only, specifies number of trailers
pulled by a vehicle. The provided value must be between 0 and 4. Defaults to 0.
:type trailers_count: int
:param shipped_hazardous_goods: 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
:type shipped_hazardous_goods: list of str
:param limited_weight: Truck routing only, vehicle weight including
trailers and shipped goods, in tons. The provided value must be between 0 and 1000.
:type limited_weight: int
:param weight_per_axle: Truck routing only, vehicle weight per axle in tons.
The provided value must be between 0 and 1000.
:type weight_per_axle: int
:param height: Truck routing only, vehicle height in meters.
The provided value must be between 0 and 50.
:type height: int
:param width: Truck routing only, vehicle width in meters.
The provided value must be between 0 and 50.
:type width: int
:param length: Truck routing only, vehicle length in meters.
The provided value must be between 0 and 300.
:type length: int
:param tunnel_category: Truck routing only, specifies the tunnel category to
restrict certain route links. The route will pass only through tunnels of a less strict category.
:type tunnel_category: list of str
:param consumption_model: If you request information on consumption, you must
provide a consumption model. The possible values are default and standard.
When you specify the value standard, you must provide additional
information in the query parameter custom consumption details
:type consumption_model: str
:param custom_consumption_details: 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
:type custom_consumption_details: str
:param speed_profile: 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
:type speed_profile: str
:param dry_run: Print URL and parameters without sending the request.
:param dry_run: bool
:returns: raw JSON response
:rtype: dict
"""
self.client.base_url = (
"https://isoline.route.api.here.com/routing/7.2"