Skip to content

Routing API

Client for the HERE Routing API.

InvalidCredentialsError

Bases: HEREError

Invalid Credentials Error Type.

This error is returned if the specified token was invalid or no contract could be found for this token.

Source code in src/herepy/routing_api.py
1649
1650
1651
1652
1653
1654
1655
class InvalidCredentialsError(HEREError):
    """
    Invalid Credentials Error Type.

    This error is returned if the specified token was invalid or no contract
    could be found for this token.
    """

InvalidInputDataError

Bases: HEREError

Invalid Input Data Error Type.

This error is returned if the specified request parameters contain invalid data, such as due to wrong parameter syntax or invalid parameter combinations.

Source code in src/herepy/routing_api.py
1658
1659
1660
1661
1662
1663
1664
1665
class InvalidInputDataError(HEREError):
    """
    Invalid Input Data Error Type.

    This error is returned if the specified request parameters contain invalid
    data, such as due to wrong parameter syntax or invalid parameter
    combinations.
    """

LinkIdNotFoundError

Bases: HEREError

Link Not Found Error Type.

This error indicates that a link ID passed as input parameter could not be found in the underlying map data.

Source code in src/herepy/routing_api.py
1686
1687
1688
1689
1690
1691
1692
class LinkIdNotFoundError(HEREError):
    """
    Link Not Found Error Type.

    This error indicates that a link ID passed as input parameter could not be
    found in the underlying map data.
    """

NoRouteFoundError

Bases: HEREError

No Route Found Error Type.

This error indicates that no route could be constructed based on the input parameter.

Source code in src/herepy/routing_api.py
1677
1678
1679
1680
1681
1682
1683
class NoRouteFoundError(HEREError):
    """
    No Route Found Error Type.

    This error indicates that no route could be constructed based on the input
    parameter.
    """

RouteNotReconstructedError

Bases: HEREError

Route Not Reconstructed Error Type.

This error indicates that the RouteId is invalid (RouteId can not be decoded into valid data) or route failed to be reconstructed from the RouteId. In every case a mitigation is to re-run CalculateRoute request to acquire a new proper RouteId.

Source code in src/herepy/routing_api.py
1695
1696
1697
1698
1699
1700
1701
1702
1703
class RouteNotReconstructedError(HEREError):
    """
    Route Not Reconstructed Error Type.

    This error indicates that the RouteId is invalid (RouteId can not be
    decoded into valid data) or route failed to be reconstructed from the
    RouteId. In every case a mitigation is to re-run CalculateRoute request to
    acquire a new proper RouteId.
    """

RoutingApi

Bases: HEREApi

A python interface into the HERE Routing API.

Source code in src/herepy/routing_api.py
  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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
class RoutingApi(HEREApi):
    """A python interface into the HERE Routing API."""

    URL_CALCULATE_ROUTE = "https://route.ls.hereapi.com/routing/7.2/calculateroute.json"
    URL_CALCULATE_ROUTE_V8 = "https://router.hereapi.com/v8/routes"
    URL_CALCULATE_MATRIX = "https://matrix.router.hereapi.com/v8/matrix"

    def __init__(self, api_key: str = None, timeout: int = None):
        """
        Initialize the Routing API client.

        Args:
          api_key (str):
            API key taken from HERE Developer Portal.
          timeout (int):
            Timeout limit for requests.

        """
        super().__init__(api_key, timeout)

    def __get(
        self,
        base_url,
        data,
        key,
        response_cls,
        manipulation_key: str = None,
        keys_for_manipulation: list = None,
        headers: dict[str, str] | None = None,
    ):
        url = Utils.build_url(base_url, extra_params=data)
        if manipulation_key and keys_for_manipulation:
            for k in keys_for_manipulation:
                url = url.replace(k, manipulation_key)
        response = requests.get(url, timeout=self._timeout, headers=headers)
        json_data = json.loads(response.content.decode("utf8"))
        if response.status_code == requests.codes.OK:
            return response_cls.new_from_jsondict(json_data)
        else:
            raise error_from_routing_service_error(json_data)

    @classmethod
    def __prepare_mode_values(cls, modes):
        mode_values = ""
        for mode in modes:
            mode_values += mode.__str__() + ";"
        mode_values = mode_values[:-1]
        return mode_values

    @classmethod
    def __list_to_waypoint(cls, waypoint_a):
        return str.format("geo!{0},{1}", waypoint_a[0], waypoint_a[1])

    def _route(self, waypoint_a, waypoint_b, modes=None, departure=None, arrival=None):
        if isinstance(waypoint_a, str):
            waypoint_a = self._get_coordinates_for_location_name(waypoint_a)
        if isinstance(waypoint_b, str):
            waypoint_b = self._get_coordinates_for_location_name(waypoint_b)
        data = {
            "waypoint0": self.__list_to_waypoint(waypoint_a),
            "waypoint1": self.__list_to_waypoint(waypoint_b),
            "mode": self.__prepare_mode_values(modes),
            "apikey": self._api_key,
        }
        if departure is not None and arrival is not None:
            raise HEREError("Specify either departure or arrival, not both.")
        if departure is not None:
            departure = self._convert_datetime_to_isoformat(departure)
            data["departure"] = departure
        if arrival is not None:
            arrival = self._convert_datetime_to_isoformat(arrival)
            data["arrival"] = arrival
        response = self.__get(self.URL_CALCULATE_ROUTE, data, "response", RoutingResponse)
        route = response.response["route"]
        maneuver = route[0]["leg"][0]["maneuver"]

        if any(mode in modes for mode in [RouteMode.car, RouteMode.truck]):
            # Get Route for Car and Truck
            response.route_short = self._get_route_from_vehicle_maneuver(maneuver)
        elif any(mode in modes for mode in [RouteMode.publicTransport, RouteMode.publicTransportTimeTable]):
            # Get Route for Public Transport
            public_transport_line = route[0]["publicTransportLine"]
            response.route_short = self._get_route_from_public_transport_line(public_transport_line)
        elif any(mode in modes for mode in [RouteMode.pedestrian, RouteMode.bicycle]):
            # Get Route for Pedestrian and Biyclce
            response.route_short = self._get_route_from_non_vehicle_maneuver(maneuver)
        return response

    def bicycle_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Request a bicycle route between two points.

        Args:
          waypoint_a:
            List contains latitude and longitude in order
            or string with the location name
          waypoint_b:
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.bicycle, RouteMode.fastest]
        return self._route(waypoint_a, waypoint_b, modes, departure)

    def car_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Request a driving route between two points.

        Args:
          waypoint_a (List):
            List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.car, RouteMode.fastest]
        return self._route(waypoint_a, waypoint_b, modes, departure)

    def pedestrian_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Request a pedestrian route between two points.

        Args:
          waypoint_a (List):
            List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.pedestrian, RouteMode.fastest]
        return self._route(waypoint_a, waypoint_b, modes, departure)

    def intermediate_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        waypoint_c: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Request a route through three points.

        Args:
          waypoint_a (List):
            Starting List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            Intermediate List contains latitude and longitude in order
            or string with the location name.
          waypoint_c (List):
            Last List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.car, RouteMode.fastest]
        return self._route(waypoint_a, waypoint_b, modes, departure)

    def public_transport(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        combine_change: bool,
        modes: list[RouteMode] = None,
        departure="now",
    ) -> RoutingResponse | None:
        """
        Request a public transport route between two points.

        Args:
          waypoint_a (List):
            Starting List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            Intermediate List contains latitude and longitude in order
            or string with the location name.
          combine_change (bool):
            Enables the change manuever in the route response, which
            indicates a public transit line change.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.publicTransport, RouteMode.fastest]
        return self._route(waypoint_a, waypoint_b, modes, departure)

    def public_transport_timetable(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        combine_change: bool,
        modes: list[RouteMode] = None,
        departure: str = None,
        arrival: str = None,
    ) -> RoutingResponse | None:
        """
        Request a public transport route between two points based on timetables.

        Args:
          waypoint_a (List):
            Starting List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            Intermediate List contains latitude and longitude in order
            or string with the location name.
          combine_change (bool):
            Enables the change manuever in the route response, which
            indicates a public transit line change.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `None`.
          arrival (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `None`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.publicTransportTimeTable, RouteMode.fastest]
        return self._route(waypoint_a, waypoint_b, modes, departure, arrival)

    def location_near_motorway(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Calculate the fastest car route between two locations.

        Args:
          waypoint_a (List):
            List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.car, RouteMode.fastest]
        return self._route(waypoint_a, waypoint_b, modes, departure)

    def truck_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Calculate the fastest truck route between two locations.

        Args:
          waypoint_a (List):
            List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.truck, RouteMode.fastest]
        return self._route(waypoint_a, waypoint_b, modes, departure)

    def route_v8(
        self,
        transport_mode: RoutingTransportMode,
        origin: list[float] | str,
        destination: list[float] | str,
        via: list[list[float]] | None = None,
        departure_time: str | None = None,
        routing_mode: RoutingMode = RoutingMode.fast,
        alternatives: int | None = None,
        avoid: dict[str, list[str]] | None = None,
        exclude: dict[str, list[str]] | None = None,
        units: RoutingMetric | None = None,
        lang: str | None = None,
        return_fields: list[RoutingApiReturnField] = [RoutingApiReturnField.polyline],
        span_fields: list[RoutingApiSpanField] | None = None,
        truck: dict[str, list[str]] | None = None,
        vehicle: dict[str, list[str]] | None = None,
        scooter: dict[str, str] | None = None,
        headers: dict | None = None,
    ) -> RoutingResponseV8 | None:
        """
        Calculate the route between the given origin and destination.

        Args:
          transport_mode (RoutingTransportMode):
            Mode of transport to be used for the calculation of the route.
          origin (Union[List[float], str]):
            List contains latitude and longitude in order
            or string with the location name.
          destination (Union[List[float], str]):
            List contains latitude and longitude in order
            or string with the location name.
          via (Optional[List[List[float]]]):
            Locations defining via waypoints.
            Locations between origin and destination.
          departure_time (Optional[str]):
            Specifies the time of departure as defined by
            either date-time or full-date T partial-time in RFC 3339,
            section 5.6 (for example, 2019-06-24T01:23:45).
          routing_mode (RoutingMode):
            Specifies which optimization is applied during route calculation,
            fast as default value.
          alternatives (Optional[int]):
            Number of alternative routes to return aside from the optimal route.
          avoid (Optional[Dict[str, List[str]]]):
            Avoid routes that violate certain features of road network or
            that go through user-specified geographical bounding boxes.
            Sample use of parameter: `{"features": [controlledAccessHighway, tunnel]}`
          exclude (Optional[Dict[str, List[str]]]):
            Defines properties which will be strictly excluded from route calculation.
            Sample use of parameter:
            `{"countries": [A comma separated list of three-letter country codes (ISO-3166-1 alpha-3 code)]}`
          units (Optional[RoutingMetric]):
            Units of measurement used in guidance instructions. The default is metric.
          lang (Optional[str]):
            Default: "en-US"
            Specifies the preferred language of the response.
            The value should comply with the IETF BCP 47.
          return_fields (List[RoutingApiReturnField]):
            Defines which attributes are included in the response as part of data
            representation of a Route or Section.
          span_fields (Optional[List[RoutingApiSpanField]]):
            Defines which attributes are included in the response spans.
            For example, attributes,length will enable the fields attributes and length in the route response.
            This parameter also requires that the polyline option is set within the return parameter.
          truck (Optional[Dict[str, List[str]]]):
            Deprecated. Use `vehicle` parameter.
          vehicle (Optional[Dict[str, List[str]]]):
            Comma-separated list of vehicle-specific parameters.
            Sample use of parameter: `{"shippedHazardousGoods": [explosive, gas, flammable]}`
          scooter (Optional[Dict[str, str]]):
            Scooter specific parameters.
            Sample use of parameter: `{"allowHighway": "true"}`
          headers (Optional[dict]):
            HTTP headers for requests.
            Sample:
            X-Request-ID
            User-provided token that can be used to trace a request or
            a group of requests sent to the service.

        Returns:
          RoutingResponseV8
        Raises:
          HEREError

        """
        if isinstance(origin, str):
            origin = self._get_coordinates_for_location_name(origin)
        if isinstance(destination, str):
            destination = self._get_coordinates_for_location_name(destination)
        data = {
            "transportMode": transport_mode.__str__(),
            "origin": str.format("{0},{1}", origin[0], origin[1]),
            "destination": str.format("{0},{1}", destination[0], destination[1]),
            "apiKey": self._api_key,
        }

        via_keys = []
        if via:
            for i, v in enumerate(via):
                key = str.format("{0}{1}_", "via", i)
                via_keys.append(key)
                data[key] = str.format("{0},{1}", v[0], v[1])
        if departure_time:
            data["departureTime"] = departure_time
        data["routingMode"] = routing_mode.__str__()
        if alternatives:
            data["alternatives"] = alternatives
        if avoid:
            data["avoid"] = {key: ",".join(vals) for key, vals in avoid.items()}
        if exclude:
            data["exclude"] = {key: ",".join(vals) for key, vals in exclude.items()}
        if units:
            data["units"] = units.__str__()
        if lang:
            data["lang"] = lang
        if return_fields:
            data["return"] = ",".join([field.__str__() for field in return_fields])
        if span_fields:
            data["spans"] = ",".join([field.__str__() for field in span_fields])
        if truck:
            warn(
                "'truck' parameter is deprecated in Routing API. Use 'vehicle' parameter instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            if vehicle is None:
                vehicle = truck
        if vehicle:
            data["vehicle"] = {key: ",".join(vals) for key, vals in vehicle.items()}
        if scooter:
            data["scooter"] = scooter

        response = self.__get(
            self.URL_CALCULATE_ROUTE_V8,
            data,
            "routes",
            RoutingResponseV8,
            manipulation_key="via",
            keys_for_manipulation=via_keys,
            headers=headers,
        )
        return response

    def __prepare_matrix_request_body(
        self,
        origins: list[list[float] | str],
        destinations: list[list[float] | str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: list[float] | None = None,
        radius: int | None = None,
        profile: MatrixRoutingProfile | None = None,
        departure: str = None,
        routing_mode: MatrixRoutingMode | None = None,
        transport_mode: MatrixRoutingTransportMode | None = None,
        avoid: Avoid | None = None,
        truck: Truck | None = None,
        matrix_attributes: list[MatrixSummaryAttribute] | None = None,
    ) -> dict[str, Any]:
        region_definition: dict[str, Any] = {
            "type": matrix_type.__str__(),
        }
        if center:
            region_definition["center"] = {"lat": center[0], "lng": center[1]}
        if radius:
            region_definition["radius"] = radius
        request_body: dict[str, Any] = {"regionDefinition": region_definition}

        if profile:
            request_body["profile"] = profile.__str__()
        if departure:
            request_body["departureTime"] = departure
        if routing_mode:
            request_body["routingMode"] = routing_mode.__str__()
        if transport_mode:
            request_body["transportMode"] = transport_mode.__str__()
        if matrix_attributes:
            request_body["matrixAttributes"] = [attribute.__str__() for attribute in matrix_attributes]
        if avoid:
            request_body["avoid"] = {"features": avoid.features, "areas": avoid.areas}
        if truck:
            request_body["truck"] = {
                "shippedHazardousGoods": truck.shipped_hazardous_goods,
                "grossWeight": truck.gross_weight,
                "weightPerAxle": truck.weight_per_axle,
                "height": truck.height,
                "width": truck.width,
                "length": truck.length,
                "tunnelCategory": truck.tunnel_category,
                "axleCount": truck.axle_count,
                "type": truck.truck_type,
                "trailerCount": truck.trailer_count,
            }

        origin_list: list[dict[str, float]] = []
        for origin in origins:
            if isinstance(origin, str):
                origin_waypoint = self._get_coordinates_for_location_name(origin)
            else:
                origin_waypoint = origin
            lat_long = {"lat": origin_waypoint[0], "lng": origin_waypoint[1]}
            origin_list.append(lat_long)
        request_body["origins"] = origin_list

        destination_list: list[dict[str, float]] = []
        for destination in destinations:
            if isinstance(destination, str):
                destination_waypoint = self._get_coordinates_for_location_name(destination)
            else:
                destination_waypoint = destination
            lat_long = {"lat": destination_waypoint[0], "lng": destination_waypoint[1]}
            destination_list.append(lat_long)
        request_body["destinations"] = destination_list

        return request_body

    def sync_matrix(
        self,
        origins: list[list[float] | str],
        destinations: list[list[float] | str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: list[float] | None = None,
        radius: int | None = None,
        profile: MatrixRoutingProfile | None = None,
        departure: str = None,
        routing_mode: MatrixRoutingMode | None = None,
        transport_mode: MatrixRoutingTransportMode | None = None,
        avoid: Avoid | None = None,
        truck: Truck | None = None,
        matrix_attributes: list[MatrixSummaryAttribute] | None = None,
    ) -> RoutingMatrixResponse | None:
        """
        Sync request a matrix of route summaries between M starts and N destinations.

        Args:
          origins (List):
            List of lists of coordinates [lat,long] of start waypoints.
            or list of string with the location names.
          destinations (List):
            List of lists of coordinates [lat,long] of destination waypoints.
            or list of string with the location names.
          matrix_type (MatrixRoutingType):
            Routing type used in definition of a region in which the matrix will be calculated.
          center (Optional[List]):
            Center of region definition, latitude and longitude.
          radius (Optional[int]):
            Center  of region definition.
          profile (Optional[MatrixRoutingProfile]):
            A profile ID enables the calculation of matrices with routes of arbitrary length.
          departure (str):
            time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
          routing_mode (Optional[MatrixRoutingMode]):
            Route mode used in optimization of route calculation.
          transport_mode (Optional[MatrixRoutingTransportMode]):
            Depending on the transport mode special constraints, speed attributes and weights
            are taken into account during route calculation.
          avoid (Optional[Avoid]):
            Avoid routes that violate these properties.
          truck (Optional[Truck]):
            Different truck options to use during route calculation when transportMode = truck.
          matrix_attributes (List):
            List of MatrixSummaryAttribute enums.

        Returns:
          RoutingMatrixResponse
        Raises:
          HEREError: If an error is received from the server.

        """
        query_params = {
            "apiKey": self._api_key,
            "async": "false",
        }

        request_body = self.__prepare_matrix_request_body(
            origins=origins,
            destinations=destinations,
            matrix_type=matrix_type,
            center=center,
            radius=radius,
            profile=profile,
            departure=departure,
            routing_mode=routing_mode,
            transport_mode=transport_mode,
            avoid=avoid,
            truck=truck,
            matrix_attributes=matrix_attributes,
        )

        url = Utils.build_url(self.URL_CALCULATE_MATRIX, extra_params=query_params)
        headers = {"Content-Type": "application/json"}
        response = requests.post(url, json=request_body, headers=headers, timeout=self._timeout)
        json_data = json.loads(response.content.decode("utf8"))
        if response.status_code == requests.codes.OK:
            if json_data.get("matrix") is not None:
                return RoutingMatrixResponse.new_from_jsondict(json_data)
            else:
                raise HEREError(
                    "Error occurred on routing_api sync_matrix "
                    + sys._getframe(1).f_code.co_name
                    + " response status code "
                    + str(response.status_code)
                )
        else:
            if "title" in json_data and "cause" in json_data:
                raise HEREError(
                    str.format(
                        "routing_api sync_matrix failed! title: {0}, cause: {1}",
                        json_data["title"],
                        json_data["cause"],
                    )
                )
            else:
                raise HEREError("Error occurred on routing_api sync_matrix " + sys._getframe(1).f_code.co_name)

    def __download_file(self, fileurl: str):
        filename = os.path.basename(fileurl)
        with requests.get(fileurl, stream=True) as r:
            r.raise_for_status()
            with open(filename, "wb") as f:
                for chunk in r.iter_content(chunk_size=8192):
                    f.write(chunk)
        print(f"{filename} file saved!")
        return filename

    def __is_correct_response(self, response):
        json_data = response.json()
        if json_data.get("matrix") is not None:
            return json_data
        elif json_data.get("status") is not None:
            print("Matrix {} calculation {}".format(json_data["matrixId"], json_data["status"]))
            return False
        elif json_data.get("error") is not None and json_data.get("error_description"):
            raise HEREError(
                "Error occurred on __is_correct_response: " + json_data["error"] + ", description: " + json_data["error_description"]
            )
        elif json_data.get("title") is not None and json_data.get("status"):
            raise HEREError("Error occurred on __is_correct_response: " + json_data["title"] + ", status: " + json_data["status"])

    def async_matrix(
        self,
        token: str,
        origins: list[list[float] | str],
        destinations: list[list[float] | str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: list[float] | None = None,
        radius: int | None = None,
        profile: MatrixRoutingProfile | None = None,
        departure: str = None,
        routing_mode: MatrixRoutingMode | None = None,
        transport_mode: MatrixRoutingTransportMode | None = None,
        avoid: Avoid | None = None,
        truck: Truck | None = None,
        matrix_attributes: list[MatrixSummaryAttribute] | None = None,
    ) -> RoutingMatrixResponse | None:
        """
        Async request a matrix of route summaries between M starts and N destinations.

        Args:
          token (str):
            Bearer token required for async calls. This is the only working solution for now.
            How to create a bearer token:
            https://developer.here.com/documentation/identity-access-management/dev_guide/topics/sdk.html#step-1-register-your-application
            https://developer.here.com/documentation/identity-access-management/dev_guide/topics/postman.html
          origins (List):
            List of lists of coordinates [lat,long] of start waypoints.
            or list of string with the location names.
          destinations (List):
            List of lists of coordinates [lat,long] of destination waypoints.
            or list of string with the location names.
          matrix_type (MatrixRoutingType):
            Routing type used in definition of a region in which the matrix will be calculated.
          center (Optional[List]):
            Center of region definition, latitude and longitude.
          radius (Optional[int]):
            Center  of region definition.
          profile (Optional[MatrixRoutingProfile]):
            A profile ID enables the calculation of matrices with routes of arbitrary length.
          departure (str):
            time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
          routing_mode (Optional[MatrixRoutingMode]):
            Route mode used in optimization of route calculation.
          transport_mode (Optional[MatrixRoutingTransportMode]):
            Depending on the transport mode special constraints, speed attributes and weights
            are taken into account during route calculation.
          avoid (Optional[Avoid]):
            Avoid routes that violate these properties.
          truck (Optional[Truck]):
            Different truck options to use during route calculation when transportMode = truck.
          matrix_attributes (List):
            List of MatrixSummaryAttribute enums.

        Returns:
          RoutingMatrixResponse.

        Raises:
          HEREError: If an error is received from the server.

        """
        query_params: dict[str, str | None] = {}

        request_body = self.__prepare_matrix_request_body(
            origins=origins,
            destinations=destinations,
            matrix_type=matrix_type,
            center=center,
            radius=radius,
            profile=profile,
            departure=departure,
            routing_mode=routing_mode,
            transport_mode=transport_mode,
            avoid=avoid,
            truck=truck,
            matrix_attributes=matrix_attributes,
        )

        url = Utils.build_url(self.URL_CALCULATE_MATRIX, extra_params=query_params)
        headers = {
            "Content-Type": "application/json",
            "Authorization": str.format("Bearer {0}", token),
        }
        json_data = json.dumps(request_body)
        response = requests.post(url, json=request_body, headers=headers, timeout=self._timeout)
        if response.status_code == requests.codes.ACCEPTED:
            json_data = response.json()
            print("Matrix {} calculation {}".format(json_data["matrixId"], json_data["status"]))
            poll_url = json_data["statusUrl"]
            headers = {"Authorization": str.format("Bearer {0}", token)}
            print("Polling matrix calculation started!")
            result = polling.poll(
                lambda: requests.get(poll_url, headers=headers),
                check_success=self.__is_correct_response,
                step=5,
                poll_forever=True,
            )
            print("Polling matrix calculation completed!")
            poll_data = result.json()
            return RoutingMatrixResponse.new_from_jsondict(poll_data)
        else:
            json_data = response.json()
            if json_data.get("error") is not None and json_data.get("error_description") is not None:
                raise HEREError(
                    "Error occurred on async_matrix: " + json_data["error"] + ", description: " + json_data["error_description"]
                )
            elif json_data.get("title") is not None and json_data.get("cause") is not None:
                raise HEREError("Error occurred on async_matrix: " + json_data["title"] + ", cause: " + json_data["cause"])
            else:
                raise HEREError("Error occurred on async_matrix " + sys._getframe(1).f_code.co_name)

    def _get_coordinates_for_location_name(self, location_name: str) -> list[float]:
        """Use the Geocoder API to resolve a location name to a set of coordinates."""
        geocoder_api = GeocoderApi(self._api_key)
        try:
            geocoder_response = geocoder_api.free_form(location_name)
        except HEREError as here_error:
            raise WaypointNotFoundError(here_error.message)
        items = getattr(geocoder_response, "items", None) if geocoder_response is not None else None
        if not items:
            raise WaypointNotFoundError(f"No geocoding results found for {location_name!r}.")
        coordinates = items[0]["position"]
        return [coordinates["lat"], coordinates["lng"]]

    @staticmethod
    def _convert_datetime_to_isoformat(datetime_object):
        """Convert a datetime.datetime object to an ISO8601 string."""
        if isinstance(datetime_object, datetime.datetime):
            datetime_object = datetime_object.isoformat()
        return datetime_object

    @staticmethod
    def _get_route_from_non_vehicle_maneuver(maneuver):
        """Extract a short route description from the maneuver instructions."""
        road_names = []

        for step in maneuver:
            instruction = step["instruction"]
            try:
                road_name = instruction.split('<span class="next-street">')[1].split("</span>")[0]
                road_name = road_name.replace("(", "").replace(")", "")

                # Only add if it does not repeat
                if not road_names or road_names[-1] != road_name:
                    road_names.append(road_name)
            except IndexError:
                pass  # No street name found in this maneuver step
        route = "; ".join(list(map(str, road_names)))
        return route

    @staticmethod
    def _get_route_from_public_transport_line(public_transport_line_segment):
        """Extract a short route description from the public transport lines."""
        lines = []
        for line_info in public_transport_line_segment:
            lines.append(line_info["lineName"] + " - " + line_info["destination"])

        route = "; ".join(list(map(str, lines)))
        return route

    @staticmethod
    def _get_route_from_vehicle_maneuver(maneuver):
        """Extract a short route description from the maneuver instructions."""
        road_names = []

        for step in maneuver:
            instruction = step["instruction"]
            try:
                road_number = instruction.split('<span class="number">')[1].split("</span>")[0]
                road_name = road_number.replace("(", "").replace(")", "")

                try:
                    street_name = instruction.split('<span class="next-street">')[1].split("</span>")[0]
                    street_name = street_name.replace("(", "").replace(")", "")

                    road_name += " - " + street_name
                except IndexError:
                    pass  # No street name found in this maneuver step

                # Only add if it does not repeat
                if not road_names or road_names[-1] != road_name:
                    road_names.append(road_name)
            except IndexError:
                pass  # No road number found in this maneuver step

        route = "; ".join(list(map(str, road_names)))
        return route

    async def __get_async(
        self,
        base_url,
        data,
        key,
        response_cls,
        manipulation_key: str = None,
        keys_for_manipulation: list = None,
        headers: dict[str, str] | None = None,
    ):
        url = Utils.build_url(base_url, extra_params=data)
        if manipulation_key and keys_for_manipulation:
            for k in keys_for_manipulation:
                url = url.replace(k, manipulation_key)
        response = await self._get_async_client().get(url, timeout=self._timeout, headers=headers)
        json_data = json.loads(response.content.decode("utf8"))
        if response.status_code == 200:
            return response_cls.new_from_jsondict(json_data)
        else:
            raise error_from_routing_service_error(json_data)

    async def _route_async(self, waypoint_a, waypoint_b, modes=None, departure=None, arrival=None):
        if isinstance(waypoint_a, str):
            waypoint_a = await self._get_coordinates_for_location_name_async(waypoint_a)
        if isinstance(waypoint_b, str):
            waypoint_b = await self._get_coordinates_for_location_name_async(waypoint_b)
        data = {
            "waypoint0": self.__list_to_waypoint(waypoint_a),
            "waypoint1": self.__list_to_waypoint(waypoint_b),
            "mode": self.__prepare_mode_values(modes),
            "apikey": self._api_key,
        }
        if departure is not None and arrival is not None:
            raise HEREError("Specify either departure or arrival, not both.")
        if departure is not None:
            departure = self._convert_datetime_to_isoformat(departure)
            data["departure"] = departure
        if arrival is not None:
            arrival = self._convert_datetime_to_isoformat(arrival)
            data["arrival"] = arrival
        response = await self.__get_async(self.URL_CALCULATE_ROUTE, data, "response", RoutingResponse)
        route = response.response["route"]
        maneuver = route[0]["leg"][0]["maneuver"]

        if any(mode in modes for mode in [RouteMode.car, RouteMode.truck]):
            # Get Route for Car and Truck
            response.route_short = self._get_route_from_vehicle_maneuver(maneuver)
        elif any(mode in modes for mode in [RouteMode.publicTransport, RouteMode.publicTransportTimeTable]):
            # Get Route for Public Transport
            public_transport_line = route[0]["publicTransportLine"]
            response.route_short = self._get_route_from_public_transport_line(public_transport_line)
        elif any(mode in modes for mode in [RouteMode.pedestrian, RouteMode.bicycle]):
            # Get Route for Pedestrian and Biyclce
            response.route_short = self._get_route_from_non_vehicle_maneuver(maneuver)
        return response

    async def async_bicycle_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Request a bicycle route between two points.

        Args:
          waypoint_a:
            List contains latitude and longitude in order
            or string with the location name
          waypoint_b:
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.bicycle, RouteMode.fastest]
        return await self._route_async(waypoint_a, waypoint_b, modes, departure)

    async def async_car_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Request a driving route between two points.

        Args:
          waypoint_a (List):
            List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.car, RouteMode.fastest]
        return await self._route_async(waypoint_a, waypoint_b, modes, departure)

    async def async_pedestrian_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Request a pedestrian route between two points.

        Args:
          waypoint_a (List):
            List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.pedestrian, RouteMode.fastest]
        return await self._route_async(waypoint_a, waypoint_b, modes, departure)

    async def async_intermediate_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        waypoint_c: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Request a route through three points.

        Args:
          waypoint_a (List):
            Starting List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            Intermediate List contains latitude and longitude in order
            or string with the location name.
          waypoint_c (List):
            Last List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.car, RouteMode.fastest]
        return await self._route_async(waypoint_a, waypoint_b, modes, departure)

    async def async_public_transport(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        combine_change: bool,
        modes: list[RouteMode] = None,
        departure="now",
    ) -> RoutingResponse | None:
        """
        Request a public transport route between two points.

        Args:
          waypoint_a (List):
            Starting List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            Intermediate List contains latitude and longitude in order
            or string with the location name.
          combine_change (bool):
            Enables the change manuever in the route response, which
            indicates a public transit line change.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.publicTransport, RouteMode.fastest]
        return await self._route_async(waypoint_a, waypoint_b, modes, departure)

    async def async_public_transport_timetable(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        combine_change: bool,
        modes: list[RouteMode] = None,
        departure: str = None,
        arrival: str = None,
    ) -> RoutingResponse | None:
        """
        Request a public transport route between two points based on timetables.

        Args:
          waypoint_a (List):
            Starting List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            Intermediate List contains latitude and longitude in order
            or string with the location name.
          combine_change (bool):
            Enables the change manuever in the route response, which
            indicates a public transit line change.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `None`.
          arrival (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `None`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.publicTransportTimeTable, RouteMode.fastest]
        return await self._route_async(waypoint_a, waypoint_b, modes, departure, arrival)

    async def async_location_near_motorway(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Calculate the fastest car route between two locations.

        Args:
          waypoint_a (List):
            List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.car, RouteMode.fastest]
        return await self._route_async(waypoint_a, waypoint_b, modes, departure)

    async def async_truck_route(
        self,
        waypoint_a: list[float] | str,
        waypoint_b: list[float] | str,
        modes: list[RouteMode] = None,
        departure: str = "now",
    ) -> RoutingResponse | None:
        """
        Calculate the fastest truck route between two locations.

        Args:
          waypoint_a (List):
            List contains latitude and longitude in order
            or string with the location name.
          waypoint_b (List):
            List contains latitude and longitude in order
            or string with the location name.
          modes (List):
            List contains RouteMode enums.
          departure (str):
            Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

        Returns:
          RoutingResponse
        Raises:
          HEREError

        """
        if modes is None:
            modes = [RouteMode.truck, RouteMode.fastest]
        return await self._route_async(waypoint_a, waypoint_b, modes, departure)

    async def async_route_v8(
        self,
        transport_mode: RoutingTransportMode,
        origin: list[float] | str,
        destination: list[float] | str,
        via: list[list[float]] | None = None,
        departure_time: str | None = None,
        routing_mode: RoutingMode = RoutingMode.fast,
        alternatives: int | None = None,
        avoid: dict[str, list[str]] | None = None,
        exclude: dict[str, list[str]] | None = None,
        units: RoutingMetric | None = None,
        lang: str | None = None,
        return_fields: list[RoutingApiReturnField] = [RoutingApiReturnField.polyline],
        span_fields: list[RoutingApiSpanField] | None = None,
        truck: dict[str, list[str]] | None = None,
        vehicle: dict[str, list[str]] | None = None,
        scooter: dict[str, str] | None = None,
        headers: dict | None = None,
    ) -> RoutingResponseV8 | None:
        """
        Calculate the route between the given origin and destination.

        Args:
          transport_mode (RoutingTransportMode):
            Mode of transport to be used for the calculation of the route.
          origin (Union[List[float], str]):
            List contains latitude and longitude in order
            or string with the location name.
          destination (Union[List[float], str]):
            List contains latitude and longitude in order
            or string with the location name.
          via (Optional[List[List[float]]]):
            Locations defining via waypoints.
            Locations between origin and destination.
          departure_time (Optional[str]):
            Specifies the time of departure as defined by
            either date-time or full-date T partial-time in RFC 3339,
            section 5.6 (for example, 2019-06-24T01:23:45).
          routing_mode (RoutingMode):
            Specifies which optimization is applied during route calculation,
            fast as default value.
          alternatives (Optional[int]):
            Number of alternative routes to return aside from the optimal route.
          avoid (Optional[Dict[str, List[str]]]):
            Avoid routes that violate certain features of road network or
            that go through user-specified geographical bounding boxes.
            Sample use of parameter: `{"features": [controlledAccessHighway, tunnel]}`
          exclude (Optional[Dict[str, List[str]]]):
            Defines properties which will be strictly excluded from route calculation.
            Sample use of parameter:
            `{"countries": [A comma separated list of three-letter country codes (ISO-3166-1 alpha-3 code)]}`
          units (Optional[RoutingMetric]):
            Units of measurement used in guidance instructions. The default is metric.
          lang (Optional[str]):
            Default: "en-US"
            Specifies the preferred language of the response.
            The value should comply with the IETF BCP 47.
          return_fields (List[RoutingApiReturnField]):
            Defines which attributes are included in the response as part of data
            representation of a Route or Section.
          span_fields (Optional[List[RoutingApiSpanField]]):
            Defines which attributes are included in the response spans.
            For example, attributes,length will enable the fields attributes and length in the route response.
            This parameter also requires that the polyline option is set within the return parameter.
          truck (Optional[Dict[str, List[str]]]):
            Deprecated. Use `vehicle` parameter.
          vehicle (Optional[Dict[str, List[str]]]):
            Comma-separated list of vehicle-specific parameters.
            Sample use of parameter: `{"shippedHazardousGoods": [explosive, gas, flammable]}`
          scooter (Optional[Dict[str, str]]):
            Scooter specific parameters.
            Sample use of parameter: `{"allowHighway": "true"}`
          headers (Optional[dict]):
            HTTP headers for requests.
            Sample:
            X-Request-ID
            User-provided token that can be used to trace a request or
            a group of requests sent to the service.

        Returns:
          RoutingResponseV8
        Raises:
          HEREError

        """
        if isinstance(origin, str):
            origin = await self._get_coordinates_for_location_name_async(origin)
        if isinstance(destination, str):
            destination = await self._get_coordinates_for_location_name_async(destination)
        data = {
            "transportMode": transport_mode.__str__(),
            "origin": str.format("{0},{1}", origin[0], origin[1]),
            "destination": str.format("{0},{1}", destination[0], destination[1]),
            "apiKey": self._api_key,
        }

        via_keys = []
        if via:
            for i, v in enumerate(via):
                key = str.format("{0}{1}_", "via", i)
                via_keys.append(key)
                data[key] = str.format("{0},{1}", v[0], v[1])
        if departure_time:
            data["departureTime"] = departure_time
        data["routingMode"] = routing_mode.__str__()
        if alternatives:
            data["alternatives"] = alternatives
        if avoid:
            data["avoid"] = {key: ",".join(vals) for key, vals in avoid.items()}
        if exclude:
            data["exclude"] = {key: ",".join(vals) for key, vals in exclude.items()}
        if units:
            data["units"] = units.__str__()
        if lang:
            data["lang"] = lang
        if return_fields:
            data["return"] = ",".join([field.__str__() for field in return_fields])
        if span_fields:
            data["spans"] = ",".join([field.__str__() for field in span_fields])
        if truck:
            warn(
                "'truck' parameter is deprecated in Routing API. Use 'vehicle' parameter instead.",
                DeprecationWarning,
                stacklevel=2,
            )
            if vehicle is None:
                vehicle = truck
        if vehicle:
            data["vehicle"] = {key: ",".join(vals) for key, vals in vehicle.items()}
        if scooter:
            data["scooter"] = scooter

        response = await self.__get_async(
            self.URL_CALCULATE_ROUTE_V8,
            data,
            "routes",
            RoutingResponseV8,
            manipulation_key="via",
            keys_for_manipulation=via_keys,
            headers=headers,
        )
        return response

    async def __prepare_matrix_request_body_async(
        self,
        origins: list[list[float] | str],
        destinations: list[list[float] | str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: list[float] | None = None,
        radius: int | None = None,
        profile: MatrixRoutingProfile | None = None,
        departure: str = None,
        routing_mode: MatrixRoutingMode | None = None,
        transport_mode: MatrixRoutingTransportMode | None = None,
        avoid: Avoid | None = None,
        truck: Truck | None = None,
        matrix_attributes: list[MatrixSummaryAttribute] | None = None,
    ) -> dict[str, Any]:
        region_definition: dict[str, Any] = {
            "type": matrix_type.__str__(),
        }
        if center:
            region_definition["center"] = {"lat": center[0], "lng": center[1]}
        if radius:
            region_definition["radius"] = radius
        request_body: dict[str, Any] = {"regionDefinition": region_definition}

        if profile:
            request_body["profile"] = profile.__str__()
        if departure:
            request_body["departureTime"] = departure
        if routing_mode:
            request_body["routingMode"] = routing_mode.__str__()
        if transport_mode:
            request_body["transportMode"] = transport_mode.__str__()
        if matrix_attributes:
            request_body["matrixAttributes"] = [attribute.__str__() for attribute in matrix_attributes]
        if avoid:
            request_body["avoid"] = {"features": avoid.features, "areas": avoid.areas}
        if truck:
            request_body["truck"] = {
                "shippedHazardousGoods": truck.shipped_hazardous_goods,
                "grossWeight": truck.gross_weight,
                "weightPerAxle": truck.weight_per_axle,
                "height": truck.height,
                "width": truck.width,
                "length": truck.length,
                "tunnelCategory": truck.tunnel_category,
                "axleCount": truck.axle_count,
                "type": truck.truck_type,
                "trailerCount": truck.trailer_count,
            }

        origin_list: list[dict[str, float]] = []
        for origin in origins:
            if isinstance(origin, str):
                origin_waypoint = await self._get_coordinates_for_location_name_async(origin)
            else:
                origin_waypoint = origin
            lat_long = {"lat": origin_waypoint[0], "lng": origin_waypoint[1]}
            origin_list.append(lat_long)
        request_body["origins"] = origin_list

        destination_list: list[dict[str, float]] = []
        for destination in destinations:
            if isinstance(destination, str):
                destination_waypoint = await self._get_coordinates_for_location_name_async(destination)
            else:
                destination_waypoint = destination
            lat_long = {"lat": destination_waypoint[0], "lng": destination_waypoint[1]}
            destination_list.append(lat_long)
        request_body["destinations"] = destination_list

        return request_body

    async def async_sync_matrix(
        self,
        origins: list[list[float] | str],
        destinations: list[list[float] | str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: list[float] | None = None,
        radius: int | None = None,
        profile: MatrixRoutingProfile | None = None,
        departure: str = None,
        routing_mode: MatrixRoutingMode | None = None,
        transport_mode: MatrixRoutingTransportMode | None = None,
        avoid: Avoid | None = None,
        truck: Truck | None = None,
        matrix_attributes: list[MatrixSummaryAttribute] | None = None,
    ) -> RoutingMatrixResponse | None:
        """
        Asynchronously request a matrix of route summaries between M starts and N destinations.

        Args:
          origins (List):
            List of lists of coordinates [lat,long] of start waypoints.
            or list of string with the location names.
          destinations (List):
            List of lists of coordinates [lat,long] of destination waypoints.
            or list of string with the location names.
          matrix_type (MatrixRoutingType):
            Routing type used in definition of a region in which the matrix will be calculated.
          center (Optional[List]):
            Center of region definition, latitude and longitude.
          radius (Optional[int]):
            Center  of region definition.
          profile (Optional[MatrixRoutingProfile]):
            A profile ID enables the calculation of matrices with routes of arbitrary length.
          departure (str):
            time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
          routing_mode (Optional[MatrixRoutingMode]):
            Route mode used in optimization of route calculation.
          transport_mode (Optional[MatrixRoutingTransportMode]):
            Depending on the transport mode special constraints, speed attributes and weights
            are taken into account during route calculation.
          avoid (Optional[Avoid]):
            Avoid routes that violate these properties.
          truck (Optional[Truck]):
            Different truck options to use during route calculation when transportMode = truck.
          matrix_attributes (List):
            List of MatrixSummaryAttribute enums.

        Returns:
          RoutingMatrixResponse
        Raises:
          HEREError: If an error is received from the server.

        """
        query_params = {
            "apiKey": self._api_key,
            "async": "false",
        }

        request_body = await self.__prepare_matrix_request_body_async(
            origins=origins,
            destinations=destinations,
            matrix_type=matrix_type,
            center=center,
            radius=radius,
            profile=profile,
            departure=departure,
            routing_mode=routing_mode,
            transport_mode=transport_mode,
            avoid=avoid,
            truck=truck,
            matrix_attributes=matrix_attributes,
        )

        url = Utils.build_url(self.URL_CALCULATE_MATRIX, extra_params=query_params)
        headers = {"Content-Type": "application/json"}
        response = await self._get_async_client().post(url, json=request_body, headers=headers, timeout=self._timeout)
        json_data = json.loads(response.content.decode("utf8"))
        if response.status_code == 200:
            if json_data.get("matrix") is not None:
                return RoutingMatrixResponse.new_from_jsondict(json_data)
            else:
                raise HEREError(
                    "Error occurred on routing_api sync_matrix "
                    + sys._getframe(1).f_code.co_name
                    + " response status code "
                    + str(response.status_code)
                )
        else:
            if "title" in json_data and "cause" in json_data:
                raise HEREError(
                    str.format(
                        "routing_api sync_matrix failed! title: {0}, cause: {1}",
                        json_data["title"],
                        json_data["cause"],
                    )
                )
            else:
                raise HEREError("Error occurred on routing_api sync_matrix " + sys._getframe(1).f_code.co_name)

    async def _get_coordinates_for_location_name_async(self, location_name: str) -> list[float]:
        """Use the Geocoder API to resolve a location name to a set of coordinates."""
        geocoder_api = GeocoderApi(self._api_key, self._timeout)
        try:
            async with geocoder_api:
                geocoder_response = await geocoder_api.async_free_form(location_name)
        except HEREError as here_error:
            raise WaypointNotFoundError(here_error.message)
        items = getattr(geocoder_response, "items", None) if geocoder_response is not None else None
        if not items:
            raise WaypointNotFoundError(f"No geocoding results found for {location_name!r}.")
        coordinates = items[0]["position"]
        return [coordinates["lat"], coordinates["lng"]]

    async def __download_file_async(self, fileurl: str):
        filename = os.path.basename(fileurl)
        async with self._get_async_client().stream("GET", fileurl, timeout=self._timeout) as response:
            response.raise_for_status()
            with open(filename, "wb") as file:
                async for chunk in response.aiter_bytes(chunk_size=8192):
                    file.write(chunk)
        print(f"{filename} file saved!")
        return filename

    async def async_matrix_async(
        self,
        token: str,
        origins: list[list[float] | str],
        destinations: list[list[float] | str],
        matrix_type: MatrixRoutingType = MatrixRoutingType.world,
        center: list[float] | None = None,
        radius: int | None = None,
        profile: MatrixRoutingProfile | None = None,
        departure: str = None,
        routing_mode: MatrixRoutingMode | None = None,
        transport_mode: MatrixRoutingTransportMode | None = None,
        avoid: Avoid | None = None,
        truck: Truck | None = None,
        matrix_attributes: list[MatrixSummaryAttribute] | None = None,
    ) -> RoutingMatrixResponse | None:
        """Asynchronously request a matrix and poll until its calculation completes."""
        request_body = await self.__prepare_matrix_request_body_async(
            origins=origins,
            destinations=destinations,
            matrix_type=matrix_type,
            center=center,
            radius=radius,
            profile=profile,
            departure=departure,
            routing_mode=routing_mode,
            transport_mode=transport_mode,
            avoid=avoid,
            truck=truck,
            matrix_attributes=matrix_attributes,
        )
        url = Utils.build_url(self.URL_CALCULATE_MATRIX, extra_params={})
        headers = {
            "Content-Type": "application/json",
            "Authorization": str.format("******", token),
        }
        response = await self._get_async_client().post(url, json=request_body, headers=headers, timeout=self._timeout)
        if response.status_code != 202:
            json_data = response.json()
            if json_data.get("error") is not None and json_data.get("error_description") is not None:
                raise HEREError(
                    "Error occurred on async_matrix: " + json_data["error"] + ", description: " + json_data["error_description"]
                )
            if json_data.get("title") is not None and json_data.get("cause") is not None:
                raise HEREError("Error occurred on async_matrix: " + json_data["title"] + ", cause: " + json_data["cause"])
            raise HEREError("Error occurred on async_matrix " + sys._getframe(1).f_code.co_name)

        json_data = response.json()
        print("Matrix {} calculation {}".format(json_data["matrixId"], json_data["status"]))
        poll_url = json_data["statusUrl"]
        headers = {"Authorization": str.format("******", token)}
        print("Polling matrix calculation started!")
        while True:
            poll_response = await self._get_async_client().get(poll_url, headers=headers, timeout=self._timeout)
            poll_data = self.__is_correct_response(poll_response)
            if poll_data:
                break
            await asyncio.sleep(5)
        print("Polling matrix calculation completed!")
        return RoutingMatrixResponse.new_from_jsondict(poll_data)

__init__(api_key=None, timeout=None)

Initialize the Routing API client.

Parameters:

Name Type Description Default
api_key str

API key taken from HERE Developer Portal.

None
timeout int

Timeout limit for requests.

None
Source code in src/herepy/routing_api.py
43
44
45
46
47
48
49
50
51
52
53
54
def __init__(self, api_key: str = None, timeout: int = None):
    """
    Initialize the Routing API client.

    Args:
      api_key (str):
        API key taken from HERE Developer Portal.
      timeout (int):
        Timeout limit for requests.

    """
    super().__init__(api_key, timeout)

async_bicycle_route(waypoint_a, waypoint_b, modes=None, departure='now') async

Request a bicycle route between two points.

Parameters:

Name Type Description Default
waypoint_a list[float] | str

List contains latitude and longitude in order or string with the location name

required
waypoint_b list[float] | str

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
async def async_bicycle_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Request a bicycle route between two points.

    Args:
      waypoint_a:
        List contains latitude and longitude in order
        or string with the location name
      waypoint_b:
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.bicycle, RouteMode.fastest]
    return await self._route_async(waypoint_a, waypoint_b, modes, departure)

async_car_route(waypoint_a, waypoint_b, modes=None, departure='now') async

Request a driving route between two points.

Parameters:

Name Type Description Default
waypoint_a List

List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
async def async_car_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Request a driving route between two points.

    Args:
      waypoint_a (List):
        List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.car, RouteMode.fastest]
    return await self._route_async(waypoint_a, waypoint_b, modes, departure)

async_intermediate_route(waypoint_a, waypoint_b, waypoint_c, modes=None, departure='now') async

Request a route through three points.

Parameters:

Name Type Description Default
waypoint_a List

Starting List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

Intermediate List contains latitude and longitude in order or string with the location name.

required
waypoint_c List

Last List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
async def async_intermediate_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    waypoint_c: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Request a route through three points.

    Args:
      waypoint_a (List):
        Starting List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        Intermediate List contains latitude and longitude in order
        or string with the location name.
      waypoint_c (List):
        Last List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.car, RouteMode.fastest]
    return await self._route_async(waypoint_a, waypoint_b, modes, departure)

async_location_near_motorway(waypoint_a, waypoint_b, modes=None, departure='now') async

Calculate the fastest car route between two locations.

Parameters:

Name Type Description Default
waypoint_a List

List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
async def async_location_near_motorway(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Calculate the fastest car route between two locations.

    Args:
      waypoint_a (List):
        List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.car, RouteMode.fastest]
    return await self._route_async(waypoint_a, waypoint_b, modes, departure)

async_matrix(token, origins, destinations, matrix_type=MatrixRoutingType.world, center=None, radius=None, profile=None, departure=None, routing_mode=None, transport_mode=None, avoid=None, truck=None, matrix_attributes=None)

Async request a matrix of route summaries between M starts and N destinations.

Parameters:

Name Type Description Default
token str

Bearer token required for async calls. This is the only working solution for now. How to create a bearer token: https://developer.here.com/documentation/identity-access-management/dev_guide/topics/sdk.html#step-1-register-your-application https://developer.here.com/documentation/identity-access-management/dev_guide/topics/postman.html

required
origins List

List of lists of coordinates [lat,long] of start waypoints. or list of string with the location names.

required
destinations List

List of lists of coordinates [lat,long] of destination waypoints. or list of string with the location names.

required
matrix_type MatrixRoutingType

Routing type used in definition of a region in which the matrix will be calculated.

world
center Optional[List]

Center of region definition, latitude and longitude.

None
radius Optional[int]

Center of region definition.

None
profile Optional[MatrixRoutingProfile]

A profile ID enables the calculation of matrices with routes of arbitrary length.

None
departure str

time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'

None
routing_mode Optional[MatrixRoutingMode]

Route mode used in optimization of route calculation.

None
transport_mode Optional[MatrixRoutingTransportMode]

Depending on the transport mode special constraints, speed attributes and weights are taken into account during route calculation.

None
avoid Optional[Avoid]

Avoid routes that violate these properties.

None
truck Optional[Truck]

Different truck options to use during route calculation when transportMode = truck.

None
matrix_attributes List

List of MatrixSummaryAttribute enums.

None

Returns:

Type Description
RoutingMatrixResponse | None

RoutingMatrixResponse.

Raises:

Type Description
HEREError

If an error is received from the server.

Source code in src/herepy/routing_api.py
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
def async_matrix(
    self,
    token: str,
    origins: list[list[float] | str],
    destinations: list[list[float] | str],
    matrix_type: MatrixRoutingType = MatrixRoutingType.world,
    center: list[float] | None = None,
    radius: int | None = None,
    profile: MatrixRoutingProfile | None = None,
    departure: str = None,
    routing_mode: MatrixRoutingMode | None = None,
    transport_mode: MatrixRoutingTransportMode | None = None,
    avoid: Avoid | None = None,
    truck: Truck | None = None,
    matrix_attributes: list[MatrixSummaryAttribute] | None = None,
) -> RoutingMatrixResponse | None:
    """
    Async request a matrix of route summaries between M starts and N destinations.

    Args:
      token (str):
        Bearer token required for async calls. This is the only working solution for now.
        How to create a bearer token:
        https://developer.here.com/documentation/identity-access-management/dev_guide/topics/sdk.html#step-1-register-your-application
        https://developer.here.com/documentation/identity-access-management/dev_guide/topics/postman.html
      origins (List):
        List of lists of coordinates [lat,long] of start waypoints.
        or list of string with the location names.
      destinations (List):
        List of lists of coordinates [lat,long] of destination waypoints.
        or list of string with the location names.
      matrix_type (MatrixRoutingType):
        Routing type used in definition of a region in which the matrix will be calculated.
      center (Optional[List]):
        Center of region definition, latitude and longitude.
      radius (Optional[int]):
        Center  of region definition.
      profile (Optional[MatrixRoutingProfile]):
        A profile ID enables the calculation of matrices with routes of arbitrary length.
      departure (str):
        time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
      routing_mode (Optional[MatrixRoutingMode]):
        Route mode used in optimization of route calculation.
      transport_mode (Optional[MatrixRoutingTransportMode]):
        Depending on the transport mode special constraints, speed attributes and weights
        are taken into account during route calculation.
      avoid (Optional[Avoid]):
        Avoid routes that violate these properties.
      truck (Optional[Truck]):
        Different truck options to use during route calculation when transportMode = truck.
      matrix_attributes (List):
        List of MatrixSummaryAttribute enums.

    Returns:
      RoutingMatrixResponse.

    Raises:
      HEREError: If an error is received from the server.

    """
    query_params: dict[str, str | None] = {}

    request_body = self.__prepare_matrix_request_body(
        origins=origins,
        destinations=destinations,
        matrix_type=matrix_type,
        center=center,
        radius=radius,
        profile=profile,
        departure=departure,
        routing_mode=routing_mode,
        transport_mode=transport_mode,
        avoid=avoid,
        truck=truck,
        matrix_attributes=matrix_attributes,
    )

    url = Utils.build_url(self.URL_CALCULATE_MATRIX, extra_params=query_params)
    headers = {
        "Content-Type": "application/json",
        "Authorization": str.format("Bearer {0}", token),
    }
    json_data = json.dumps(request_body)
    response = requests.post(url, json=request_body, headers=headers, timeout=self._timeout)
    if response.status_code == requests.codes.ACCEPTED:
        json_data = response.json()
        print("Matrix {} calculation {}".format(json_data["matrixId"], json_data["status"]))
        poll_url = json_data["statusUrl"]
        headers = {"Authorization": str.format("Bearer {0}", token)}
        print("Polling matrix calculation started!")
        result = polling.poll(
            lambda: requests.get(poll_url, headers=headers),
            check_success=self.__is_correct_response,
            step=5,
            poll_forever=True,
        )
        print("Polling matrix calculation completed!")
        poll_data = result.json()
        return RoutingMatrixResponse.new_from_jsondict(poll_data)
    else:
        json_data = response.json()
        if json_data.get("error") is not None and json_data.get("error_description") is not None:
            raise HEREError(
                "Error occurred on async_matrix: " + json_data["error"] + ", description: " + json_data["error_description"]
            )
        elif json_data.get("title") is not None and json_data.get("cause") is not None:
            raise HEREError("Error occurred on async_matrix: " + json_data["title"] + ", cause: " + json_data["cause"])
        else:
            raise HEREError("Error occurred on async_matrix " + sys._getframe(1).f_code.co_name)

async_matrix_async(token, origins, destinations, matrix_type=MatrixRoutingType.world, center=None, radius=None, profile=None, departure=None, routing_mode=None, transport_mode=None, avoid=None, truck=None, matrix_attributes=None) async

Asynchronously request a matrix and poll until its calculation completes.

Source code in src/herepy/routing_api.py
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
async def async_matrix_async(
    self,
    token: str,
    origins: list[list[float] | str],
    destinations: list[list[float] | str],
    matrix_type: MatrixRoutingType = MatrixRoutingType.world,
    center: list[float] | None = None,
    radius: int | None = None,
    profile: MatrixRoutingProfile | None = None,
    departure: str = None,
    routing_mode: MatrixRoutingMode | None = None,
    transport_mode: MatrixRoutingTransportMode | None = None,
    avoid: Avoid | None = None,
    truck: Truck | None = None,
    matrix_attributes: list[MatrixSummaryAttribute] | None = None,
) -> RoutingMatrixResponse | None:
    """Asynchronously request a matrix and poll until its calculation completes."""
    request_body = await self.__prepare_matrix_request_body_async(
        origins=origins,
        destinations=destinations,
        matrix_type=matrix_type,
        center=center,
        radius=radius,
        profile=profile,
        departure=departure,
        routing_mode=routing_mode,
        transport_mode=transport_mode,
        avoid=avoid,
        truck=truck,
        matrix_attributes=matrix_attributes,
    )
    url = Utils.build_url(self.URL_CALCULATE_MATRIX, extra_params={})
    headers = {
        "Content-Type": "application/json",
        "Authorization": str.format("******", token),
    }
    response = await self._get_async_client().post(url, json=request_body, headers=headers, timeout=self._timeout)
    if response.status_code != 202:
        json_data = response.json()
        if json_data.get("error") is not None and json_data.get("error_description") is not None:
            raise HEREError(
                "Error occurred on async_matrix: " + json_data["error"] + ", description: " + json_data["error_description"]
            )
        if json_data.get("title") is not None and json_data.get("cause") is not None:
            raise HEREError("Error occurred on async_matrix: " + json_data["title"] + ", cause: " + json_data["cause"])
        raise HEREError("Error occurred on async_matrix " + sys._getframe(1).f_code.co_name)

    json_data = response.json()
    print("Matrix {} calculation {}".format(json_data["matrixId"], json_data["status"]))
    poll_url = json_data["statusUrl"]
    headers = {"Authorization": str.format("******", token)}
    print("Polling matrix calculation started!")
    while True:
        poll_response = await self._get_async_client().get(poll_url, headers=headers, timeout=self._timeout)
        poll_data = self.__is_correct_response(poll_response)
        if poll_data:
            break
        await asyncio.sleep(5)
    print("Polling matrix calculation completed!")
    return RoutingMatrixResponse.new_from_jsondict(poll_data)

async_pedestrian_route(waypoint_a, waypoint_b, modes=None, departure='now') async

Request a pedestrian route between two points.

Parameters:

Name Type Description Default
waypoint_a List

List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
async def async_pedestrian_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Request a pedestrian route between two points.

    Args:
      waypoint_a (List):
        List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.pedestrian, RouteMode.fastest]
    return await self._route_async(waypoint_a, waypoint_b, modes, departure)

async_public_transport(waypoint_a, waypoint_b, combine_change, modes=None, departure='now') async

Request a public transport route between two points.

Parameters:

Name Type Description Default
waypoint_a List

Starting List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

Intermediate List contains latitude and longitude in order or string with the location name.

required
combine_change bool

Enables the change manuever in the route response, which indicates a public transit line change.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
async def async_public_transport(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    combine_change: bool,
    modes: list[RouteMode] = None,
    departure="now",
) -> RoutingResponse | None:
    """
    Request a public transport route between two points.

    Args:
      waypoint_a (List):
        Starting List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        Intermediate List contains latitude and longitude in order
        or string with the location name.
      combine_change (bool):
        Enables the change manuever in the route response, which
        indicates a public transit line change.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.publicTransport, RouteMode.fastest]
    return await self._route_async(waypoint_a, waypoint_b, modes, departure)

async_public_transport_timetable(waypoint_a, waypoint_b, combine_change, modes=None, departure=None, arrival=None) async

Request a public transport route between two points based on timetables.

Parameters:

Name Type Description Default
waypoint_a List

Starting List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

Intermediate List contains latitude and longitude in order or string with the location name.

required
combine_change bool

Enables the change manuever in the route response, which indicates a public transit line change.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default None.

None
arrival str

Date time str in format yyyy-mm-ddThh:mm:ss. Default None.

None

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
async def async_public_transport_timetable(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    combine_change: bool,
    modes: list[RouteMode] = None,
    departure: str = None,
    arrival: str = None,
) -> RoutingResponse | None:
    """
    Request a public transport route between two points based on timetables.

    Args:
      waypoint_a (List):
        Starting List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        Intermediate List contains latitude and longitude in order
        or string with the location name.
      combine_change (bool):
        Enables the change manuever in the route response, which
        indicates a public transit line change.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `None`.
      arrival (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `None`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.publicTransportTimeTable, RouteMode.fastest]
    return await self._route_async(waypoint_a, waypoint_b, modes, departure, arrival)

async_route_v8(transport_mode, origin, destination, via=None, departure_time=None, routing_mode=RoutingMode.fast, alternatives=None, avoid=None, exclude=None, units=None, lang=None, return_fields=[RoutingApiReturnField.polyline], span_fields=None, truck=None, vehicle=None, scooter=None, headers=None) async

Calculate the route between the given origin and destination.

Parameters:

Name Type Description Default
transport_mode RoutingTransportMode

Mode of transport to be used for the calculation of the route.

required
origin Union[List[float], str]

List contains latitude and longitude in order or string with the location name.

required
destination Union[List[float], str]

List contains latitude and longitude in order or string with the location name.

required
via Optional[List[List[float]]]

Locations defining via waypoints. Locations between origin and destination.

None
departure_time Optional[str]

Specifies the time of departure as defined by either date-time or full-date T partial-time in RFC 3339, section 5.6 (for example, 2019-06-24T01:23:45).

None
routing_mode RoutingMode

Specifies which optimization is applied during route calculation, fast as default value.

fast
alternatives Optional[int]

Number of alternative routes to return aside from the optimal route.

None
avoid Optional[Dict[str, List[str]]]

Avoid routes that violate certain features of road network or that go through user-specified geographical bounding boxes. Sample use of parameter: {"features": [controlledAccessHighway, tunnel]}

None
exclude Optional[Dict[str, List[str]]]

Defines properties which will be strictly excluded from route calculation. Sample use of parameter: {"countries": [A comma separated list of three-letter country codes (ISO-3166-1 alpha-3 code)]}

None
units Optional[RoutingMetric]

Units of measurement used in guidance instructions. The default is metric.

None
lang Optional[str]

Default: "en-US" Specifies the preferred language of the response. The value should comply with the IETF BCP 47.

None
return_fields List[RoutingApiReturnField]

Defines which attributes are included in the response as part of data representation of a Route or Section.

[polyline]
span_fields Optional[List[RoutingApiSpanField]]

Defines which attributes are included in the response spans. For example, attributes,length will enable the fields attributes and length in the route response. This parameter also requires that the polyline option is set within the return parameter.

None
truck Optional[Dict[str, List[str]]]

Deprecated. Use vehicle parameter.

None
vehicle Optional[Dict[str, List[str]]]

Comma-separated list of vehicle-specific parameters. Sample use of parameter: {"shippedHazardousGoods": [explosive, gas, flammable]}

None
scooter Optional[Dict[str, str]]

Scooter specific parameters. Sample use of parameter: {"allowHighway": "true"}

None
headers Optional[dict]

HTTP headers for requests. Sample: X-Request-ID User-provided token that can be used to trace a request or a group of requests sent to the service.

None

Returns:

Type Description
RoutingResponseV8 | None

RoutingResponseV8

Raises: HEREError

Source code in src/herepy/routing_api.py
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
async def async_route_v8(
    self,
    transport_mode: RoutingTransportMode,
    origin: list[float] | str,
    destination: list[float] | str,
    via: list[list[float]] | None = None,
    departure_time: str | None = None,
    routing_mode: RoutingMode = RoutingMode.fast,
    alternatives: int | None = None,
    avoid: dict[str, list[str]] | None = None,
    exclude: dict[str, list[str]] | None = None,
    units: RoutingMetric | None = None,
    lang: str | None = None,
    return_fields: list[RoutingApiReturnField] = [RoutingApiReturnField.polyline],
    span_fields: list[RoutingApiSpanField] | None = None,
    truck: dict[str, list[str]] | None = None,
    vehicle: dict[str, list[str]] | None = None,
    scooter: dict[str, str] | None = None,
    headers: dict | None = None,
) -> RoutingResponseV8 | None:
    """
    Calculate the route between the given origin and destination.

    Args:
      transport_mode (RoutingTransportMode):
        Mode of transport to be used for the calculation of the route.
      origin (Union[List[float], str]):
        List contains latitude and longitude in order
        or string with the location name.
      destination (Union[List[float], str]):
        List contains latitude and longitude in order
        or string with the location name.
      via (Optional[List[List[float]]]):
        Locations defining via waypoints.
        Locations between origin and destination.
      departure_time (Optional[str]):
        Specifies the time of departure as defined by
        either date-time or full-date T partial-time in RFC 3339,
        section 5.6 (for example, 2019-06-24T01:23:45).
      routing_mode (RoutingMode):
        Specifies which optimization is applied during route calculation,
        fast as default value.
      alternatives (Optional[int]):
        Number of alternative routes to return aside from the optimal route.
      avoid (Optional[Dict[str, List[str]]]):
        Avoid routes that violate certain features of road network or
        that go through user-specified geographical bounding boxes.
        Sample use of parameter: `{"features": [controlledAccessHighway, tunnel]}`
      exclude (Optional[Dict[str, List[str]]]):
        Defines properties which will be strictly excluded from route calculation.
        Sample use of parameter:
        `{"countries": [A comma separated list of three-letter country codes (ISO-3166-1 alpha-3 code)]}`
      units (Optional[RoutingMetric]):
        Units of measurement used in guidance instructions. The default is metric.
      lang (Optional[str]):
        Default: "en-US"
        Specifies the preferred language of the response.
        The value should comply with the IETF BCP 47.
      return_fields (List[RoutingApiReturnField]):
        Defines which attributes are included in the response as part of data
        representation of a Route or Section.
      span_fields (Optional[List[RoutingApiSpanField]]):
        Defines which attributes are included in the response spans.
        For example, attributes,length will enable the fields attributes and length in the route response.
        This parameter also requires that the polyline option is set within the return parameter.
      truck (Optional[Dict[str, List[str]]]):
        Deprecated. Use `vehicle` parameter.
      vehicle (Optional[Dict[str, List[str]]]):
        Comma-separated list of vehicle-specific parameters.
        Sample use of parameter: `{"shippedHazardousGoods": [explosive, gas, flammable]}`
      scooter (Optional[Dict[str, str]]):
        Scooter specific parameters.
        Sample use of parameter: `{"allowHighway": "true"}`
      headers (Optional[dict]):
        HTTP headers for requests.
        Sample:
        X-Request-ID
        User-provided token that can be used to trace a request or
        a group of requests sent to the service.

    Returns:
      RoutingResponseV8
    Raises:
      HEREError

    """
    if isinstance(origin, str):
        origin = await self._get_coordinates_for_location_name_async(origin)
    if isinstance(destination, str):
        destination = await self._get_coordinates_for_location_name_async(destination)
    data = {
        "transportMode": transport_mode.__str__(),
        "origin": str.format("{0},{1}", origin[0], origin[1]),
        "destination": str.format("{0},{1}", destination[0], destination[1]),
        "apiKey": self._api_key,
    }

    via_keys = []
    if via:
        for i, v in enumerate(via):
            key = str.format("{0}{1}_", "via", i)
            via_keys.append(key)
            data[key] = str.format("{0},{1}", v[0], v[1])
    if departure_time:
        data["departureTime"] = departure_time
    data["routingMode"] = routing_mode.__str__()
    if alternatives:
        data["alternatives"] = alternatives
    if avoid:
        data["avoid"] = {key: ",".join(vals) for key, vals in avoid.items()}
    if exclude:
        data["exclude"] = {key: ",".join(vals) for key, vals in exclude.items()}
    if units:
        data["units"] = units.__str__()
    if lang:
        data["lang"] = lang
    if return_fields:
        data["return"] = ",".join([field.__str__() for field in return_fields])
    if span_fields:
        data["spans"] = ",".join([field.__str__() for field in span_fields])
    if truck:
        warn(
            "'truck' parameter is deprecated in Routing API. Use 'vehicle' parameter instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        if vehicle is None:
            vehicle = truck
    if vehicle:
        data["vehicle"] = {key: ",".join(vals) for key, vals in vehicle.items()}
    if scooter:
        data["scooter"] = scooter

    response = await self.__get_async(
        self.URL_CALCULATE_ROUTE_V8,
        data,
        "routes",
        RoutingResponseV8,
        manipulation_key="via",
        keys_for_manipulation=via_keys,
        headers=headers,
    )
    return response

async_sync_matrix(origins, destinations, matrix_type=MatrixRoutingType.world, center=None, radius=None, profile=None, departure=None, routing_mode=None, transport_mode=None, avoid=None, truck=None, matrix_attributes=None) async

Asynchronously request a matrix of route summaries between M starts and N destinations.

Parameters:

Name Type Description Default
origins List

List of lists of coordinates [lat,long] of start waypoints. or list of string with the location names.

required
destinations List

List of lists of coordinates [lat,long] of destination waypoints. or list of string with the location names.

required
matrix_type MatrixRoutingType

Routing type used in definition of a region in which the matrix will be calculated.

world
center Optional[List]

Center of region definition, latitude and longitude.

None
radius Optional[int]

Center of region definition.

None
profile Optional[MatrixRoutingProfile]

A profile ID enables the calculation of matrices with routes of arbitrary length.

None
departure str

time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'

None
routing_mode Optional[MatrixRoutingMode]

Route mode used in optimization of route calculation.

None
transport_mode Optional[MatrixRoutingTransportMode]

Depending on the transport mode special constraints, speed attributes and weights are taken into account during route calculation.

None
avoid Optional[Avoid]

Avoid routes that violate these properties.

None
truck Optional[Truck]

Different truck options to use during route calculation when transportMode = truck.

None
matrix_attributes List

List of MatrixSummaryAttribute enums.

None

Returns:

Type Description
RoutingMatrixResponse | None

RoutingMatrixResponse

Raises: HEREError: If an error is received from the server.

Source code in src/herepy/routing_api.py
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
async def async_sync_matrix(
    self,
    origins: list[list[float] | str],
    destinations: list[list[float] | str],
    matrix_type: MatrixRoutingType = MatrixRoutingType.world,
    center: list[float] | None = None,
    radius: int | None = None,
    profile: MatrixRoutingProfile | None = None,
    departure: str = None,
    routing_mode: MatrixRoutingMode | None = None,
    transport_mode: MatrixRoutingTransportMode | None = None,
    avoid: Avoid | None = None,
    truck: Truck | None = None,
    matrix_attributes: list[MatrixSummaryAttribute] | None = None,
) -> RoutingMatrixResponse | None:
    """
    Asynchronously request a matrix of route summaries between M starts and N destinations.

    Args:
      origins (List):
        List of lists of coordinates [lat,long] of start waypoints.
        or list of string with the location names.
      destinations (List):
        List of lists of coordinates [lat,long] of destination waypoints.
        or list of string with the location names.
      matrix_type (MatrixRoutingType):
        Routing type used in definition of a region in which the matrix will be calculated.
      center (Optional[List]):
        Center of region definition, latitude and longitude.
      radius (Optional[int]):
        Center  of region definition.
      profile (Optional[MatrixRoutingProfile]):
        A profile ID enables the calculation of matrices with routes of arbitrary length.
      departure (str):
        time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
      routing_mode (Optional[MatrixRoutingMode]):
        Route mode used in optimization of route calculation.
      transport_mode (Optional[MatrixRoutingTransportMode]):
        Depending on the transport mode special constraints, speed attributes and weights
        are taken into account during route calculation.
      avoid (Optional[Avoid]):
        Avoid routes that violate these properties.
      truck (Optional[Truck]):
        Different truck options to use during route calculation when transportMode = truck.
      matrix_attributes (List):
        List of MatrixSummaryAttribute enums.

    Returns:
      RoutingMatrixResponse
    Raises:
      HEREError: If an error is received from the server.

    """
    query_params = {
        "apiKey": self._api_key,
        "async": "false",
    }

    request_body = await self.__prepare_matrix_request_body_async(
        origins=origins,
        destinations=destinations,
        matrix_type=matrix_type,
        center=center,
        radius=radius,
        profile=profile,
        departure=departure,
        routing_mode=routing_mode,
        transport_mode=transport_mode,
        avoid=avoid,
        truck=truck,
        matrix_attributes=matrix_attributes,
    )

    url = Utils.build_url(self.URL_CALCULATE_MATRIX, extra_params=query_params)
    headers = {"Content-Type": "application/json"}
    response = await self._get_async_client().post(url, json=request_body, headers=headers, timeout=self._timeout)
    json_data = json.loads(response.content.decode("utf8"))
    if response.status_code == 200:
        if json_data.get("matrix") is not None:
            return RoutingMatrixResponse.new_from_jsondict(json_data)
        else:
            raise HEREError(
                "Error occurred on routing_api sync_matrix "
                + sys._getframe(1).f_code.co_name
                + " response status code "
                + str(response.status_code)
            )
    else:
        if "title" in json_data and "cause" in json_data:
            raise HEREError(
                str.format(
                    "routing_api sync_matrix failed! title: {0}, cause: {1}",
                    json_data["title"],
                    json_data["cause"],
                )
            )
        else:
            raise HEREError("Error occurred on routing_api sync_matrix " + sys._getframe(1).f_code.co_name)

async_truck_route(waypoint_a, waypoint_b, modes=None, departure='now') async

Calculate the fastest truck route between two locations.

Parameters:

Name Type Description Default
waypoint_a List

List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
async def async_truck_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Calculate the fastest truck route between two locations.

    Args:
      waypoint_a (List):
        List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.truck, RouteMode.fastest]
    return await self._route_async(waypoint_a, waypoint_b, modes, departure)

bicycle_route(waypoint_a, waypoint_b, modes=None, departure='now')

Request a bicycle route between two points.

Parameters:

Name Type Description Default
waypoint_a list[float] | str

List contains latitude and longitude in order or string with the location name

required
waypoint_b list[float] | str

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def bicycle_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Request a bicycle route between two points.

    Args:
      waypoint_a:
        List contains latitude and longitude in order
        or string with the location name
      waypoint_b:
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.bicycle, RouteMode.fastest]
    return self._route(waypoint_a, waypoint_b, modes, departure)

car_route(waypoint_a, waypoint_b, modes=None, departure='now')

Request a driving route between two points.

Parameters:

Name Type Description Default
waypoint_a List

List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def car_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Request a driving route between two points.

    Args:
      waypoint_a (List):
        List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.car, RouteMode.fastest]
    return self._route(waypoint_a, waypoint_b, modes, departure)

intermediate_route(waypoint_a, waypoint_b, waypoint_c, modes=None, departure='now')

Request a route through three points.

Parameters:

Name Type Description Default
waypoint_a List

Starting List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

Intermediate List contains latitude and longitude in order or string with the location name.

required
waypoint_c List

Last List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def intermediate_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    waypoint_c: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Request a route through three points.

    Args:
      waypoint_a (List):
        Starting List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        Intermediate List contains latitude and longitude in order
        or string with the location name.
      waypoint_c (List):
        Last List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.car, RouteMode.fastest]
    return self._route(waypoint_a, waypoint_b, modes, departure)

location_near_motorway(waypoint_a, waypoint_b, modes=None, departure='now')

Calculate the fastest car route between two locations.

Parameters:

Name Type Description Default
waypoint_a List

List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def location_near_motorway(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Calculate the fastest car route between two locations.

    Args:
      waypoint_a (List):
        List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.car, RouteMode.fastest]
    return self._route(waypoint_a, waypoint_b, modes, departure)

pedestrian_route(waypoint_a, waypoint_b, modes=None, departure='now')

Request a pedestrian route between two points.

Parameters:

Name Type Description Default
waypoint_a List

List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def pedestrian_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Request a pedestrian route between two points.

    Args:
      waypoint_a (List):
        List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.pedestrian, RouteMode.fastest]
    return self._route(waypoint_a, waypoint_b, modes, departure)

public_transport(waypoint_a, waypoint_b, combine_change, modes=None, departure='now')

Request a public transport route between two points.

Parameters:

Name Type Description Default
waypoint_a List

Starting List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

Intermediate List contains latitude and longitude in order or string with the location name.

required
combine_change bool

Enables the change manuever in the route response, which indicates a public transit line change.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def public_transport(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    combine_change: bool,
    modes: list[RouteMode] = None,
    departure="now",
) -> RoutingResponse | None:
    """
    Request a public transport route between two points.

    Args:
      waypoint_a (List):
        Starting List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        Intermediate List contains latitude and longitude in order
        or string with the location name.
      combine_change (bool):
        Enables the change manuever in the route response, which
        indicates a public transit line change.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.publicTransport, RouteMode.fastest]
    return self._route(waypoint_a, waypoint_b, modes, departure)

public_transport_timetable(waypoint_a, waypoint_b, combine_change, modes=None, departure=None, arrival=None)

Request a public transport route between two points based on timetables.

Parameters:

Name Type Description Default
waypoint_a List

Starting List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

Intermediate List contains latitude and longitude in order or string with the location name.

required
combine_change bool

Enables the change manuever in the route response, which indicates a public transit line change.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default None.

None
arrival str

Date time str in format yyyy-mm-ddThh:mm:ss. Default None.

None

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def public_transport_timetable(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    combine_change: bool,
    modes: list[RouteMode] = None,
    departure: str = None,
    arrival: str = None,
) -> RoutingResponse | None:
    """
    Request a public transport route between two points based on timetables.

    Args:
      waypoint_a (List):
        Starting List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        Intermediate List contains latitude and longitude in order
        or string with the location name.
      combine_change (bool):
        Enables the change manuever in the route response, which
        indicates a public transit line change.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `None`.
      arrival (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `None`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.publicTransportTimeTable, RouteMode.fastest]
    return self._route(waypoint_a, waypoint_b, modes, departure, arrival)

route_v8(transport_mode, origin, destination, via=None, departure_time=None, routing_mode=RoutingMode.fast, alternatives=None, avoid=None, exclude=None, units=None, lang=None, return_fields=[RoutingApiReturnField.polyline], span_fields=None, truck=None, vehicle=None, scooter=None, headers=None)

Calculate the route between the given origin and destination.

Parameters:

Name Type Description Default
transport_mode RoutingTransportMode

Mode of transport to be used for the calculation of the route.

required
origin Union[List[float], str]

List contains latitude and longitude in order or string with the location name.

required
destination Union[List[float], str]

List contains latitude and longitude in order or string with the location name.

required
via Optional[List[List[float]]]

Locations defining via waypoints. Locations between origin and destination.

None
departure_time Optional[str]

Specifies the time of departure as defined by either date-time or full-date T partial-time in RFC 3339, section 5.6 (for example, 2019-06-24T01:23:45).

None
routing_mode RoutingMode

Specifies which optimization is applied during route calculation, fast as default value.

fast
alternatives Optional[int]

Number of alternative routes to return aside from the optimal route.

None
avoid Optional[Dict[str, List[str]]]

Avoid routes that violate certain features of road network or that go through user-specified geographical bounding boxes. Sample use of parameter: {"features": [controlledAccessHighway, tunnel]}

None
exclude Optional[Dict[str, List[str]]]

Defines properties which will be strictly excluded from route calculation. Sample use of parameter: {"countries": [A comma separated list of three-letter country codes (ISO-3166-1 alpha-3 code)]}

None
units Optional[RoutingMetric]

Units of measurement used in guidance instructions. The default is metric.

None
lang Optional[str]

Default: "en-US" Specifies the preferred language of the response. The value should comply with the IETF BCP 47.

None
return_fields List[RoutingApiReturnField]

Defines which attributes are included in the response as part of data representation of a Route or Section.

[polyline]
span_fields Optional[List[RoutingApiSpanField]]

Defines which attributes are included in the response spans. For example, attributes,length will enable the fields attributes and length in the route response. This parameter also requires that the polyline option is set within the return parameter.

None
truck Optional[Dict[str, List[str]]]

Deprecated. Use vehicle parameter.

None
vehicle Optional[Dict[str, List[str]]]

Comma-separated list of vehicle-specific parameters. Sample use of parameter: {"shippedHazardousGoods": [explosive, gas, flammable]}

None
scooter Optional[Dict[str, str]]

Scooter specific parameters. Sample use of parameter: {"allowHighway": "true"}

None
headers Optional[dict]

HTTP headers for requests. Sample: X-Request-ID User-provided token that can be used to trace a request or a group of requests sent to the service.

None

Returns:

Type Description
RoutingResponseV8 | None

RoutingResponseV8

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def route_v8(
    self,
    transport_mode: RoutingTransportMode,
    origin: list[float] | str,
    destination: list[float] | str,
    via: list[list[float]] | None = None,
    departure_time: str | None = None,
    routing_mode: RoutingMode = RoutingMode.fast,
    alternatives: int | None = None,
    avoid: dict[str, list[str]] | None = None,
    exclude: dict[str, list[str]] | None = None,
    units: RoutingMetric | None = None,
    lang: str | None = None,
    return_fields: list[RoutingApiReturnField] = [RoutingApiReturnField.polyline],
    span_fields: list[RoutingApiSpanField] | None = None,
    truck: dict[str, list[str]] | None = None,
    vehicle: dict[str, list[str]] | None = None,
    scooter: dict[str, str] | None = None,
    headers: dict | None = None,
) -> RoutingResponseV8 | None:
    """
    Calculate the route between the given origin and destination.

    Args:
      transport_mode (RoutingTransportMode):
        Mode of transport to be used for the calculation of the route.
      origin (Union[List[float], str]):
        List contains latitude and longitude in order
        or string with the location name.
      destination (Union[List[float], str]):
        List contains latitude and longitude in order
        or string with the location name.
      via (Optional[List[List[float]]]):
        Locations defining via waypoints.
        Locations between origin and destination.
      departure_time (Optional[str]):
        Specifies the time of departure as defined by
        either date-time or full-date T partial-time in RFC 3339,
        section 5.6 (for example, 2019-06-24T01:23:45).
      routing_mode (RoutingMode):
        Specifies which optimization is applied during route calculation,
        fast as default value.
      alternatives (Optional[int]):
        Number of alternative routes to return aside from the optimal route.
      avoid (Optional[Dict[str, List[str]]]):
        Avoid routes that violate certain features of road network or
        that go through user-specified geographical bounding boxes.
        Sample use of parameter: `{"features": [controlledAccessHighway, tunnel]}`
      exclude (Optional[Dict[str, List[str]]]):
        Defines properties which will be strictly excluded from route calculation.
        Sample use of parameter:
        `{"countries": [A comma separated list of three-letter country codes (ISO-3166-1 alpha-3 code)]}`
      units (Optional[RoutingMetric]):
        Units of measurement used in guidance instructions. The default is metric.
      lang (Optional[str]):
        Default: "en-US"
        Specifies the preferred language of the response.
        The value should comply with the IETF BCP 47.
      return_fields (List[RoutingApiReturnField]):
        Defines which attributes are included in the response as part of data
        representation of a Route or Section.
      span_fields (Optional[List[RoutingApiSpanField]]):
        Defines which attributes are included in the response spans.
        For example, attributes,length will enable the fields attributes and length in the route response.
        This parameter also requires that the polyline option is set within the return parameter.
      truck (Optional[Dict[str, List[str]]]):
        Deprecated. Use `vehicle` parameter.
      vehicle (Optional[Dict[str, List[str]]]):
        Comma-separated list of vehicle-specific parameters.
        Sample use of parameter: `{"shippedHazardousGoods": [explosive, gas, flammable]}`
      scooter (Optional[Dict[str, str]]):
        Scooter specific parameters.
        Sample use of parameter: `{"allowHighway": "true"}`
      headers (Optional[dict]):
        HTTP headers for requests.
        Sample:
        X-Request-ID
        User-provided token that can be used to trace a request or
        a group of requests sent to the service.

    Returns:
      RoutingResponseV8
    Raises:
      HEREError

    """
    if isinstance(origin, str):
        origin = self._get_coordinates_for_location_name(origin)
    if isinstance(destination, str):
        destination = self._get_coordinates_for_location_name(destination)
    data = {
        "transportMode": transport_mode.__str__(),
        "origin": str.format("{0},{1}", origin[0], origin[1]),
        "destination": str.format("{0},{1}", destination[0], destination[1]),
        "apiKey": self._api_key,
    }

    via_keys = []
    if via:
        for i, v in enumerate(via):
            key = str.format("{0}{1}_", "via", i)
            via_keys.append(key)
            data[key] = str.format("{0},{1}", v[0], v[1])
    if departure_time:
        data["departureTime"] = departure_time
    data["routingMode"] = routing_mode.__str__()
    if alternatives:
        data["alternatives"] = alternatives
    if avoid:
        data["avoid"] = {key: ",".join(vals) for key, vals in avoid.items()}
    if exclude:
        data["exclude"] = {key: ",".join(vals) for key, vals in exclude.items()}
    if units:
        data["units"] = units.__str__()
    if lang:
        data["lang"] = lang
    if return_fields:
        data["return"] = ",".join([field.__str__() for field in return_fields])
    if span_fields:
        data["spans"] = ",".join([field.__str__() for field in span_fields])
    if truck:
        warn(
            "'truck' parameter is deprecated in Routing API. Use 'vehicle' parameter instead.",
            DeprecationWarning,
            stacklevel=2,
        )
        if vehicle is None:
            vehicle = truck
    if vehicle:
        data["vehicle"] = {key: ",".join(vals) for key, vals in vehicle.items()}
    if scooter:
        data["scooter"] = scooter

    response = self.__get(
        self.URL_CALCULATE_ROUTE_V8,
        data,
        "routes",
        RoutingResponseV8,
        manipulation_key="via",
        keys_for_manipulation=via_keys,
        headers=headers,
    )
    return response

sync_matrix(origins, destinations, matrix_type=MatrixRoutingType.world, center=None, radius=None, profile=None, departure=None, routing_mode=None, transport_mode=None, avoid=None, truck=None, matrix_attributes=None)

Sync request a matrix of route summaries between M starts and N destinations.

Parameters:

Name Type Description Default
origins List

List of lists of coordinates [lat,long] of start waypoints. or list of string with the location names.

required
destinations List

List of lists of coordinates [lat,long] of destination waypoints. or list of string with the location names.

required
matrix_type MatrixRoutingType

Routing type used in definition of a region in which the matrix will be calculated.

world
center Optional[List]

Center of region definition, latitude and longitude.

None
radius Optional[int]

Center of region definition.

None
profile Optional[MatrixRoutingProfile]

A profile ID enables the calculation of matrices with routes of arbitrary length.

None
departure str

time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'

None
routing_mode Optional[MatrixRoutingMode]

Route mode used in optimization of route calculation.

None
transport_mode Optional[MatrixRoutingTransportMode]

Depending on the transport mode special constraints, speed attributes and weights are taken into account during route calculation.

None
avoid Optional[Avoid]

Avoid routes that violate these properties.

None
truck Optional[Truck]

Different truck options to use during route calculation when transportMode = truck.

None
matrix_attributes List

List of MatrixSummaryAttribute enums.

None

Returns:

Type Description
RoutingMatrixResponse | None

RoutingMatrixResponse

Raises: HEREError: If an error is received from the server.

Source code in src/herepy/routing_api.py
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
def sync_matrix(
    self,
    origins: list[list[float] | str],
    destinations: list[list[float] | str],
    matrix_type: MatrixRoutingType = MatrixRoutingType.world,
    center: list[float] | None = None,
    radius: int | None = None,
    profile: MatrixRoutingProfile | None = None,
    departure: str = None,
    routing_mode: MatrixRoutingMode | None = None,
    transport_mode: MatrixRoutingTransportMode | None = None,
    avoid: Avoid | None = None,
    truck: Truck | None = None,
    matrix_attributes: list[MatrixSummaryAttribute] | None = None,
) -> RoutingMatrixResponse | None:
    """
    Sync request a matrix of route summaries between M starts and N destinations.

    Args:
      origins (List):
        List of lists of coordinates [lat,long] of start waypoints.
        or list of string with the location names.
      destinations (List):
        List of lists of coordinates [lat,long] of destination waypoints.
        or list of string with the location names.
      matrix_type (MatrixRoutingType):
        Routing type used in definition of a region in which the matrix will be calculated.
      center (Optional[List]):
        Center of region definition, latitude and longitude.
      radius (Optional[int]):
        Center  of region definition.
      profile (Optional[MatrixRoutingProfile]):
        A profile ID enables the calculation of matrices with routes of arbitrary length.
      departure (str):
        time when travel is expected to start, e.g.: '2013-07-04T17:00:00+02'
      routing_mode (Optional[MatrixRoutingMode]):
        Route mode used in optimization of route calculation.
      transport_mode (Optional[MatrixRoutingTransportMode]):
        Depending on the transport mode special constraints, speed attributes and weights
        are taken into account during route calculation.
      avoid (Optional[Avoid]):
        Avoid routes that violate these properties.
      truck (Optional[Truck]):
        Different truck options to use during route calculation when transportMode = truck.
      matrix_attributes (List):
        List of MatrixSummaryAttribute enums.

    Returns:
      RoutingMatrixResponse
    Raises:
      HEREError: If an error is received from the server.

    """
    query_params = {
        "apiKey": self._api_key,
        "async": "false",
    }

    request_body = self.__prepare_matrix_request_body(
        origins=origins,
        destinations=destinations,
        matrix_type=matrix_type,
        center=center,
        radius=radius,
        profile=profile,
        departure=departure,
        routing_mode=routing_mode,
        transport_mode=transport_mode,
        avoid=avoid,
        truck=truck,
        matrix_attributes=matrix_attributes,
    )

    url = Utils.build_url(self.URL_CALCULATE_MATRIX, extra_params=query_params)
    headers = {"Content-Type": "application/json"}
    response = requests.post(url, json=request_body, headers=headers, timeout=self._timeout)
    json_data = json.loads(response.content.decode("utf8"))
    if response.status_code == requests.codes.OK:
        if json_data.get("matrix") is not None:
            return RoutingMatrixResponse.new_from_jsondict(json_data)
        else:
            raise HEREError(
                "Error occurred on routing_api sync_matrix "
                + sys._getframe(1).f_code.co_name
                + " response status code "
                + str(response.status_code)
            )
    else:
        if "title" in json_data and "cause" in json_data:
            raise HEREError(
                str.format(
                    "routing_api sync_matrix failed! title: {0}, cause: {1}",
                    json_data["title"],
                    json_data["cause"],
                )
            )
        else:
            raise HEREError("Error occurred on routing_api sync_matrix " + sys._getframe(1).f_code.co_name)

truck_route(waypoint_a, waypoint_b, modes=None, departure='now')

Calculate the fastest truck route between two locations.

Parameters:

Name Type Description Default
waypoint_a List

List contains latitude and longitude in order or string with the location name.

required
waypoint_b List

List contains latitude and longitude in order or string with the location name.

required
modes List

List contains RouteMode enums.

None
departure str

Date time str in format yyyy-mm-ddThh:mm:ss. Default now.

'now'

Returns:

Type Description
RoutingResponse | None

RoutingResponse

Raises: HEREError

Source code in src/herepy/routing_api.py
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
def truck_route(
    self,
    waypoint_a: list[float] | str,
    waypoint_b: list[float] | str,
    modes: list[RouteMode] = None,
    departure: str = "now",
) -> RoutingResponse | None:
    """
    Calculate the fastest truck route between two locations.

    Args:
      waypoint_a (List):
        List contains latitude and longitude in order
        or string with the location name.
      waypoint_b (List):
        List contains latitude and longitude in order
        or string with the location name.
      modes (List):
        List contains RouteMode enums.
      departure (str):
        Date time str in format `yyyy-mm-ddThh:mm:ss`. Default `now`.

    Returns:
      RoutingResponse
    Raises:
      HEREError

    """
    if modes is None:
        modes = [RouteMode.truck, RouteMode.fastest]
    return self._route(waypoint_a, waypoint_b, modes, departure)

WaypointNotFoundError

Bases: HEREError

Waypoint not found Error Type.

This error indicates that one of the requested waypoints (start/end or via point) could not be found in the routing network.

Source code in src/herepy/routing_api.py
1668
1669
1670
1671
1672
1673
1674
class WaypointNotFoundError(HEREError):
    """
    Waypoint not found Error Type.

    This error indicates that one of the requested waypoints
    (start/end or via point) could not be found in the routing network.
    """

error_from_routing_service_error(json_data)

Return the correct error class for routing errors.

Source code in src/herepy/routing_api.py
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
def error_from_routing_service_error(json_data):
    """Return the correct error class for routing errors."""
    if "error" in json_data:
        return _auth_error(json_data)
    elif "status" in json_data:
        return _status_error(json_data)
    elif "subtype" in json_data:
        return _request_error(json_data)
    else:
        return _default_error(json_data)