everymap-providers-here 0.2.2

HERE Technologies provider for EveryMap — geocoding, routing, traffic, isolines, and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
pub mod types;

use crate::client::HereClient;
use async_trait::async_trait;
use everymap_core::domains::matching::{
    MatchedPoint, MatchingOptions, RouteMatcher, TraceResponse,
};
use everymap_core::error::EveryMapResult;
use everymap_core::types::Coordinate;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

pub use types::*;

const MATCHING_BASE_URL: &str = "https://routematching.hereapi.com/v8";

/// Exhaustive options for HERE Route Matching API v8.
/// Organized into groups matching the API parameter structure.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HereMatchingOptions {
    // --- Match mode ---
    pub route_match: Option<u8>,
    pub mode: Option<MatchMode>,
    pub routing_mode: Option<MatchRoutingMode>,
    pub traffic: Option<MatchTrafficMode>,
    pub legal: Option<LegalConstraint>,
    pub traverse_gates: Option<bool>,
    pub oneway: Option<bool>,

    // --- Matching parameters ---
    pub map_match_radius: Option<u32>,
    pub align_to_gps_time: Option<bool>,
    pub ignore_zero_speed_points: Option<bool>,
    #[deprecated(since = "0.2.1", note = "Use `waypoint_distance` instead")]
    pub wp_dist: Option<u32>,
    pub waypoint_distance: Option<u32>,
    pub speed_fc_cat: Option<String>,
    pub map_match_tolerance: Option<u32>,
    pub heading: Option<f64>,

    // --- Vehicle dimensions & weight ---
    pub limited_weight: Option<u32>,
    pub height: Option<u32>,
    pub length: Option<u32>,
    pub width: Option<u32>,
    pub vehicle_number_axles: Option<u32>,
    pub trailer_number_axles: Option<u32>,
    pub trailer_type: Option<TrailerType>,
    pub vehicle_weight: Option<u32>,
    pub trailer_weight: Option<u32>,
    pub weight_per_axle: Option<u32>,
    pub height_above_1st_axle: Option<u32>,
    pub trailers_count: Option<u32>,

    // --- Emission & fuel ---
    pub emission_type: Option<EmissionType>,
    pub co2_emission_class: Option<u32>,
    pub fuel_type: Option<MatchFuelType>,
    pub hybrid: Option<bool>,

    // --- Restrictions ---
    pub avoid_links: Option<Vec<String>>,
    pub avoid_areas: Option<Vec<String>>,
    pub avoid_turns: Option<Vec<String>>,
    pub avoid_features: Option<Vec<AvoidFeature>>,
    pub avoid_private: Option<bool>,
    pub avoid_country_change: Option<bool>,
    pub shipped_hazardous_goods: Option<Vec<HazardousGoodsType>>,
    pub tunnel_category: Option<TunnelCategory>,

    // --- Commercial ---
    pub commercial: Option<bool>,
    pub passengers_count: Option<u32>,
    pub tires_count: Option<u32>,
    pub disabled_equipped: Option<bool>,
    pub license_plate: Option<String>,

    // --- Time ---
    pub departure: Option<String>,
    pub arrival: Option<String>,

    // --- Response attributes ---
    pub leg_attributes: Option<String>,
    pub link_attributes: Option<String>,
    pub response_attributes: Option<String>,
    pub route_attributes: Option<String>,
    pub meta_attributes: Option<String>,
    pub maneuver_attributes: Option<String>,
    pub instruction_format: Option<InstructionFormat>,
    pub language: Option<String>,

    // --- Toll ---
    pub toll_vehicle_type: Option<u32>,
    pub toll_pass: Option<String>,
    pub currency: Option<String>,
    pub driver_cost: Option<String>,
    pub vehicle_cost: Option<String>,
    pub vehicle_cost_on_ferry: Option<String>,
    pub cost_per_consumption_unit: Option<String>,

    // --- Advanced ---
    pub max_speed: Option<u32>,
    pub alternatives: Option<u32>,
    pub truck_verified: Option<bool>,
    pub ignore_waypoint_vehicle_restriction: Option<bool>,
    pub admin_truck_restrictions: Option<bool>,
    pub ignore_preferred_routes: Option<bool>,
    pub exclude_zone_types: Option<String>,
    pub overlays: Option<String>,
    pub custom_restrict_limit: Option<String>,
    pub custom_attributes: Option<String>,
    pub custom_consumption_details: Option<String>,
    pub timeout: Option<u32>,
    pub driving_report: Option<bool>,
    pub ehorizon_limits: Option<String>,
}

/// Implementation of RouteMatcher for HERE Technologies.
pub struct HereRouteMatcher {
    pub(crate) client: Arc<HereClient>,
    pub(crate) base_url: String,
}

impl HereRouteMatcher {
    pub fn new(client: Arc<HereClient>) -> Self {
        Self {
            client,
            base_url: MATCHING_BASE_URL.to_string(),
        }
    }

    pub fn with_base_url(client: Arc<HereClient>, base_url: String) -> Self {
        Self { client, base_url }
    }
}

/// Wire format: `{"response": {"route": [{"waypoint": [...], "leg": [...], "mode": {...}}]}}`
#[derive(Debug, Deserialize)]
struct HereMatchApiResponseWrapper {
    #[serde(default)]
    response: HereMatchApiResponseInner,
}

#[derive(Debug, Default, Deserialize)]
struct HereMatchApiResponseInner {
    #[serde(default)]
    route: Vec<HereMatchApiRoute>,
}

#[derive(Debug, Default, Deserialize)]
struct HereMatchApiRoute {
    #[serde(default)]
    waypoint: Vec<HereMatchApiWaypoint>,
    #[serde(default)]
    leg: Vec<HereMatchApiLeg>,
}

#[derive(Debug, Default, Deserialize)]
#[allow(dead_code)] // Deserialize-only struct; fields only accessed via serde derive
struct HereMatchApiWaypoint {
    #[serde(default, rename = "mappedPosition")]
    mapped_position: Option<HereMatchApiPosition>,
    #[serde(default, rename = "originalPosition")]
    original_position: Option<HereMatchApiPosition>,
    #[serde(default, rename = "confidenceValue")]
    confidence_value: Option<f64>,
    #[serde(default, rename = "matchDistance")]
    match_distance: Option<f64>,
}

#[derive(Debug, Default, Deserialize)]
struct HereMatchApiPosition {
    #[serde(default)]
    latitude: f64,
    #[serde(default)]
    longitude: f64,
}

#[derive(Debug, Default, Deserialize)]
struct HereMatchApiLeg {
    #[serde(default)]
    length: f64,
    #[serde(default, rename = "travelTime")]
    travel_time: f64,
}

impl From<HereMatchedPoint> for MatchedPoint {
    fn from(p: HereMatchedPoint) -> Self {
        Self {
            coordinate: Coordinate::new(p.lat.unwrap_or(0.0), p.lng.unwrap_or(0.0))
                .unwrap_or(Coordinate::ORIGIN),
            confidence: p.point_match_probability,
            road_name: None,
        }
    }
}

fn add_option(
    params: &mut Vec<(String, String)>,
    key: &str,
    value: Option<impl std::fmt::Display>,
) {
    if let Some(v) = value {
        params.push((key.to_string(), v.to_string()));
    }
}

fn add_option_ref(params: &mut Vec<(String, String)>, key: &str, value: Option<&String>) {
    if let Some(v) = value {
        params.push((key.to_string(), v.clone()));
    }
}

/// Convert core `MatchingOptions` to HERE-specific `HereMatchingOptions`,
/// extracting common fields and parsing `provider_extra` for HERE-specific ones.
fn matching_options_from_core(options: &MatchingOptions) -> HereMatchingOptions {
    let mut here_options = HereMatchingOptions {
        heading: options.heading,
        departure: options.departure_time.as_ref().map(|dt| dt.to_string()),
        ..Default::default()
    };

    // Convert avoid types
    if !options.avoid.is_empty() {
        here_options.avoid_features = Some(
            options
                .avoid
                .iter()
                .map(|a| match a {
                    everymap_core::domains::routing::AvoidType::Tolls => AvoidFeature::TollRoad,
                    everymap_core::domains::routing::AvoidType::Ferries => AvoidFeature::Ferry,
                    everymap_core::domains::routing::AvoidType::Tunnels => AvoidFeature::Tunnel,
                    everymap_core::domains::routing::AvoidType::Highways => {
                        AvoidFeature::ControlledAccessHighway
                    }
                    everymap_core::domains::routing::AvoidType::DirtRoads => AvoidFeature::DirtRoad,
                })
                .collect(),
        );
    }

    // Convert core transport_mode to HERE match mode (provider_extra can still override)
    if let Some(transport_mode) = &options.transport_mode {
        here_options.mode = match transport_mode {
            everymap_core::domains::routing::TransportMode::Car => Some(MatchMode::Car),
            everymap_core::domains::routing::TransportMode::Truck => Some(MatchMode::Truck),
            everymap_core::domains::routing::TransportMode::Pedestrian => {
                Some(MatchMode::Pedestrian)
            }
            everymap_core::domains::routing::TransportMode::Bicycle => Some(MatchMode::Bicycle),
            everymap_core::domains::routing::TransportMode::Bus => Some(MatchMode::Bus),
            everymap_core::domains::routing::TransportMode::Scooter => Some(MatchMode::Motorcycle),
            everymap_core::domains::routing::TransportMode::Taxi => Some(MatchMode::Taxi),
            _ => Some(MatchMode::Car),
        };
    }

    // Extract HERE-specific options from provider_extra
    if let Some(extra) = &options.provider_extra {
        if let Some(obj) = extra.as_object() {
            if let Some(v) = obj.get("route_match").and_then(|v| v.as_u64()) {
                here_options.route_match = Some(v as u8);
            }
            if let Some(v) = obj.get("mode") {
                here_options.mode = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("routing_mode") {
                here_options.routing_mode = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("traffic") {
                here_options.traffic = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("legal") {
                here_options.legal = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("traverse_gates").and_then(|v| v.as_bool()) {
                here_options.traverse_gates = Some(v);
            }
            if let Some(v) = obj.get("oneway").and_then(|v| v.as_bool()) {
                here_options.oneway = Some(v);
            }
            if let Some(v) = obj.get("map_match_radius").and_then(|v| v.as_u64()) {
                here_options.map_match_radius = Some(v as u32);
            }
            if let Some(v) = obj.get("align_to_gps_time").and_then(|v| v.as_bool()) {
                here_options.align_to_gps_time = Some(v);
            }
            if let Some(v) = obj
                .get("ignore_zero_speed_points")
                .and_then(|v| v.as_bool())
            {
                here_options.ignore_zero_speed_points = Some(v);
            }
            #[allow(deprecated)]
            {
                if let Some(v) = obj.get("wp_dist").and_then(|v| v.as_u64()) {
                    here_options.wp_dist = Some(v as u32);
                }
            }
            if let Some(v) = obj.get("waypoint_distance").and_then(|v| v.as_u64()) {
                here_options.waypoint_distance = Some(v as u32);
            }
            if let Some(v) = obj.get("speed_fc_cat").and_then(|v| v.as_str()) {
                here_options.speed_fc_cat = Some(v.to_string());
            }
            if let Some(v) = obj.get("map_match_tolerance").and_then(|v| v.as_u64()) {
                here_options.map_match_tolerance = Some(v as u32);
            }
            if let Some(v) = obj.get("limited_weight").and_then(|v| v.as_u64()) {
                here_options.limited_weight = Some(v as u32);
            }
            if let Some(v) = obj.get("height").and_then(|v| v.as_u64()) {
                here_options.height = Some(v as u32);
            }
            if let Some(v) = obj.get("length").and_then(|v| v.as_u64()) {
                here_options.length = Some(v as u32);
            }
            if let Some(v) = obj.get("width").and_then(|v| v.as_u64()) {
                here_options.width = Some(v as u32);
            }
            if let Some(v) = obj.get("vehicle_number_axles").and_then(|v| v.as_u64()) {
                here_options.vehicle_number_axles = Some(v as u32);
            }
            if let Some(v) = obj.get("trailer_number_axles").and_then(|v| v.as_u64()) {
                here_options.trailer_number_axles = Some(v as u32);
            }
            if let Some(v) = obj.get("trailer_type") {
                here_options.trailer_type = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("vehicle_weight").and_then(|v| v.as_u64()) {
                here_options.vehicle_weight = Some(v as u32);
            }
            if let Some(v) = obj.get("trailer_weight").and_then(|v| v.as_u64()) {
                here_options.trailer_weight = Some(v as u32);
            }
            if let Some(v) = obj.get("weight_per_axle").and_then(|v| v.as_u64()) {
                here_options.weight_per_axle = Some(v as u32);
            }
            if let Some(v) = obj.get("height_above_1st_axle").and_then(|v| v.as_u64()) {
                here_options.height_above_1st_axle = Some(v as u32);
            }
            if let Some(v) = obj.get("trailers_count").and_then(|v| v.as_u64()) {
                here_options.trailers_count = Some(v as u32);
            }
            if let Some(v) = obj.get("emission_type") {
                here_options.emission_type = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("co2_emission_class").and_then(|v| v.as_u64()) {
                here_options.co2_emission_class = Some(v as u32);
            }
            if let Some(v) = obj.get("fuel_type") {
                here_options.fuel_type = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("hybrid").and_then(|v| v.as_bool()) {
                here_options.hybrid = Some(v);
            }
            if let Some(v) = obj.get("avoid_links").and_then(|v| v.as_array()) {
                here_options.avoid_links = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("avoid_areas").and_then(|v| v.as_array()) {
                here_options.avoid_areas = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("avoid_turns").and_then(|v| v.as_array()) {
                here_options.avoid_turns = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("avoid_private").and_then(|v| v.as_bool()) {
                here_options.avoid_private = Some(v);
            }
            if let Some(v) = obj.get("avoid_country_change").and_then(|v| v.as_bool()) {
                here_options.avoid_country_change = Some(v);
            }
            if let Some(v) = obj
                .get("shipped_hazardous_goods")
                .and_then(|v| v.as_array())
            {
                here_options.shipped_hazardous_goods = Some(
                    v.iter()
                        .filter_map(|i| serde_json::from_value(i.clone()).ok())
                        .collect(),
                );
            }
            if let Some(v) = obj.get("tunnel_category") {
                here_options.tunnel_category = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("commercial").and_then(|v| v.as_bool()) {
                here_options.commercial = Some(v);
            }
            if let Some(v) = obj.get("passengers_count").and_then(|v| v.as_u64()) {
                here_options.passengers_count = Some(v as u32);
            }
            if let Some(v) = obj.get("tires_count").and_then(|v| v.as_u64()) {
                here_options.tires_count = Some(v as u32);
            }
            if let Some(v) = obj.get("disabled_equipped").and_then(|v| v.as_bool()) {
                here_options.disabled_equipped = Some(v);
            }
            if let Some(v) = obj.get("license_plate").and_then(|v| v.as_str()) {
                here_options.license_plate = Some(v.to_string());
            }
            if let Some(v) = obj.get("arrival").and_then(|v| v.as_str()) {
                here_options.arrival = Some(v.to_string());
            }
            if let Some(v) = obj.get("leg_attributes").and_then(|v| v.as_str()) {
                here_options.leg_attributes = Some(v.to_string());
            }
            if let Some(v) = obj.get("link_attributes").and_then(|v| v.as_str()) {
                here_options.link_attributes = Some(v.to_string());
            }
            if let Some(v) = obj.get("response_attributes").and_then(|v| v.as_str()) {
                here_options.response_attributes = Some(v.to_string());
            }
            if let Some(v) = obj.get("route_attributes").and_then(|v| v.as_str()) {
                here_options.route_attributes = Some(v.to_string());
            }
            if let Some(v) = obj.get("meta_attributes").and_then(|v| v.as_str()) {
                here_options.meta_attributes = Some(v.to_string());
            }
            if let Some(v) = obj.get("maneuver_attributes").and_then(|v| v.as_str()) {
                here_options.maneuver_attributes = Some(v.to_string());
            }
            if let Some(v) = obj.get("instruction_format") {
                here_options.instruction_format = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("toll_vehicle_type").and_then(|v| v.as_u64()) {
                here_options.toll_vehicle_type = Some(v as u32);
            }
            if let Some(v) = obj.get("toll_pass").and_then(|v| v.as_str()) {
                here_options.toll_pass = Some(v.to_string());
            }
            if let Some(v) = obj.get("currency").and_then(|v| v.as_str()) {
                here_options.currency = Some(v.to_string());
            }
            if let Some(v) = obj.get("driver_cost").and_then(|v| v.as_str()) {
                here_options.driver_cost = Some(v.to_string());
            }
            if let Some(v) = obj.get("vehicle_cost").and_then(|v| v.as_str()) {
                here_options.vehicle_cost = Some(v.to_string());
            }
            if let Some(v) = obj.get("vehicle_cost_on_ferry").and_then(|v| v.as_str()) {
                here_options.vehicle_cost_on_ferry = Some(v.to_string());
            }
            if let Some(v) = obj
                .get("cost_per_consumption_unit")
                .and_then(|v| v.as_str())
            {
                here_options.cost_per_consumption_unit = Some(v.to_string());
            }
            if let Some(v) = obj.get("max_speed").and_then(|v| v.as_u64()) {
                here_options.max_speed = Some(v as u32);
            }
            if let Some(v) = obj.get("alternatives").and_then(|v| v.as_u64()) {
                here_options.alternatives = Some(v as u32);
            }
            if let Some(v) = obj.get("truck_verified").and_then(|v| v.as_bool()) {
                here_options.truck_verified = Some(v);
            }
            if let Some(v) = obj
                .get("ignore_waypoint_vehicle_restriction")
                .and_then(|v| v.as_bool())
            {
                here_options.ignore_waypoint_vehicle_restriction = Some(v);
            }
            if let Some(v) = obj
                .get("admin_truck_restrictions")
                .and_then(|v| v.as_bool())
            {
                here_options.admin_truck_restrictions = Some(v);
            }
            if let Some(v) = obj.get("ignore_preferred_routes").and_then(|v| v.as_bool()) {
                here_options.ignore_preferred_routes = Some(v);
            }
            if let Some(v) = obj.get("exclude_zone_types").and_then(|v| v.as_str()) {
                here_options.exclude_zone_types = Some(v.to_string());
            }
            if let Some(v) = obj.get("overlays").and_then(|v| v.as_str()) {
                here_options.overlays = Some(v.to_string());
            }
            if let Some(v) = obj.get("custom_restrict_limit").and_then(|v| v.as_str()) {
                here_options.custom_restrict_limit = Some(v.to_string());
            }
            if let Some(v) = obj.get("custom_attributes").and_then(|v| v.as_str()) {
                here_options.custom_attributes = Some(v.to_string());
            }
            if let Some(v) = obj
                .get("custom_consumption_details")
                .and_then(|v| v.as_str())
            {
                here_options.custom_consumption_details = Some(v.to_string());
            }
            if let Some(v) = obj.get("timeout").and_then(|v| v.as_u64()) {
                here_options.timeout = Some(v as u32);
            }
            if let Some(v) = obj.get("driving_report").and_then(|v| v.as_bool()) {
                here_options.driving_report = Some(v);
            }
            if let Some(v) = obj.get("ehorizon_limits").and_then(|v| v.as_str()) {
                here_options.ehorizon_limits = Some(v.to_string());
            }
            // Convert transport_mode from core
            if let Some(v) = obj.get("transport_mode") {
                if let Ok(transport_mode) = serde_json::from_value::<
                    everymap_core::domains::routing::TransportMode,
                >(v.clone())
                {
                    here_options.mode = match transport_mode {
                        everymap_core::domains::routing::TransportMode::Car => Some(MatchMode::Car),
                        everymap_core::domains::routing::TransportMode::Truck => {
                            Some(MatchMode::Truck)
                        }
                        everymap_core::domains::routing::TransportMode::Pedestrian => {
                            Some(MatchMode::Pedestrian)
                        }
                        everymap_core::domains::routing::TransportMode::Bicycle => {
                            Some(MatchMode::Bicycle)
                        }
                        everymap_core::domains::routing::TransportMode::Bus => Some(MatchMode::Bus),
                        everymap_core::domains::routing::TransportMode::Scooter => {
                            Some(MatchMode::Motorcycle)
                        }
                        everymap_core::domains::routing::TransportMode::Taxi => {
                            Some(MatchMode::Taxi)
                        }
                        everymap_core::domains::routing::TransportMode::Unknown => {
                            Some(MatchMode::Car)
                        }
                    };
                }
            }
        }
    }

    // Default to car mode if none specified
    if here_options.mode.is_none() {
        here_options.mode = Some(MatchMode::Car);
    }
    // Default routing mode to fastest if none specified
    if here_options.routing_mode.is_none() {
        here_options.routing_mode = Some(MatchRoutingMode::Fastest);
    }
    // Default traffic to disabled if none specified
    if here_options.traffic.is_none() {
        here_options.traffic = Some(MatchTrafficMode::Disabled);
    }

    here_options
}

#[async_trait]
impl RouteMatcher for HereRouteMatcher {
    async fn match_route(
        &self,
        points: &[Coordinate],
        options: &MatchingOptions,
    ) -> EveryMapResult<TraceResponse> {
        let options = matching_options_from_core(options);

        // Use waypointN format: waypoint0=lat,lng&waypoint1=lat,lng&...
        let mut params: Vec<(String, String)> = vec![];
        for (i, p) in points.iter().enumerate() {
            params.push((format!("waypoint{}", i), format!("{},{}", p.lat, p.lng)));
        }

        // Default to routeMatch=1 if not specified
        if options.route_match.is_none() {
            params.push(("routeMatch".to_string(), "1".to_string()));
        }

        let options = &options;

        // Match mode — compound format: {routing_type};{transport_mode}[;traffic:{enabled|disabled}]
        add_option(&mut params, "routeMatch", options.route_match);
        {
            let routing = match &options.routing_mode {
                Some(MatchRoutingMode::Shortest) => "shortest",
                _ => "fastest",
            };
            let transport = match &options.mode {
                Some(m) => crate::util::enum_as_str(m),
                None => "car".to_string(),
            };
            let traffic = match &options.traffic {
                Some(MatchTrafficMode::Enabled) => ";traffic:enabled",
                _ => ";traffic:disabled",
            };
            params.push((
                "mode".to_string(),
                format!("{};{}{}", routing, transport, traffic),
            ));
        }
        if let Some(legal) = &options.legal {
            params.push(("legal".to_string(), crate::util::enum_as_str(legal)));
        }
        add_option(&mut params, "traverseGates", options.traverse_gates);
        add_option(&mut params, "oneway", options.oneway);

        // Matching parameters
        add_option(&mut params, "mapMatchRadius", options.map_match_radius);
        add_option(&mut params, "alignToGpsTime", options.align_to_gps_time);
        add_option(
            &mut params,
            "ignoreZeroSpeedPoints",
            options.ignore_zero_speed_points,
        );
        let wp_dist = {
            #[allow(deprecated)]
            options.waypoint_distance.or(options.wp_dist)
        };
        add_option(&mut params, "wpDist", wp_dist);
        add_option_ref(&mut params, "speedFcCat", options.speed_fc_cat.as_ref());
        add_option(
            &mut params,
            "mapMatchTolerance",
            options.map_match_tolerance,
        );
        add_option(&mut params, "heading", options.heading);

        // Vehicle dimensions
        add_option(&mut params, "limitedWeight", options.limited_weight);
        add_option(&mut params, "height", options.height);
        add_option(&mut params, "length", options.length);
        add_option(&mut params, "width", options.width);
        add_option(
            &mut params,
            "vehicleNumberAxles",
            options.vehicle_number_axles,
        );
        add_option(
            &mut params,
            "trailerNumberAxles",
            options.trailer_number_axles,
        );
        if let Some(tt) = &options.trailer_type {
            params.push(("trailerType".to_string(), crate::util::enum_as_str(tt)));
        }
        add_option(&mut params, "vehicleWeight", options.vehicle_weight);
        add_option(&mut params, "trailerWeight", options.trailer_weight);
        add_option(&mut params, "weightPerAxle", options.weight_per_axle);
        add_option(
            &mut params,
            "heightAbove1stAxle",
            options.height_above_1st_axle,
        );
        add_option(&mut params, "trailersCount", options.trailers_count);

        // Emission & fuel
        if let Some(et) = &options.emission_type {
            params.push(("emissionType".to_string(), crate::util::enum_as_str(et)));
        }
        add_option(&mut params, "co2EmissionClass", options.co2_emission_class);
        if let Some(ft) = &options.fuel_type {
            params.push(("fuelType".to_string(), crate::util::enum_as_str(ft)));
        }
        add_option(&mut params, "hybrid", options.hybrid);

        // Restrictions
        if let Some(links) = &options.avoid_links {
            params.push(("avoidLinks".to_string(), links.join(",")));
        }
        if let Some(areas) = &options.avoid_areas {
            params.push(("avoidAreas".to_string(), areas.join(",")));
        }
        if let Some(turns) = &options.avoid_turns {
            params.push(("avoidTurns".to_string(), turns.join(",")));
        }
        if let Some(af) = &options.avoid_features {
            params.push((
                "avoidFeatures".to_string(),
                af.iter()
                    .map(crate::util::enum_as_str)
                    .collect::<Vec<_>>()
                    .join(","),
            ));
        }
        add_option(&mut params, "avoidPrivate", options.avoid_private);
        add_option(
            &mut params,
            "avoidCountryChange",
            options.avoid_country_change,
        );
        if let Some(hg) = &options.shipped_hazardous_goods {
            params.push((
                "shippedHazardousGoods".to_string(),
                hg.iter()
                    .map(crate::util::enum_as_str)
                    .collect::<Vec<_>>()
                    .join(","),
            ));
        }
        if let Some(tc) = &options.tunnel_category {
            params.push(("tunnelCategory".to_string(), crate::util::enum_as_str(tc)));
        }

        // Commercial
        add_option(&mut params, "commercial", options.commercial);
        add_option(&mut params, "passengersCount", options.passengers_count);
        add_option(&mut params, "tiresCount", options.tires_count);
        add_option(&mut params, "disabledEquipped", options.disabled_equipped);
        add_option_ref(&mut params, "licensePlate", options.license_plate.as_ref());

        // Time
        add_option_ref(&mut params, "departure", options.departure.as_ref());
        add_option_ref(&mut params, "arrival", options.arrival.as_ref());

        // Response attributes
        add_option_ref(
            &mut params,
            "legAttributes",
            options.leg_attributes.as_ref(),
        );
        add_option_ref(
            &mut params,
            "linkAttributes",
            options.link_attributes.as_ref(),
        );
        add_option_ref(
            &mut params,
            "responseAttributes",
            options.response_attributes.as_ref(),
        );
        add_option_ref(
            &mut params,
            "routeAttributes",
            options.route_attributes.as_ref(),
        );
        add_option_ref(
            &mut params,
            "metaAttributes",
            options.meta_attributes.as_ref(),
        );
        add_option_ref(
            &mut params,
            "maneuverAttributes",
            options.maneuver_attributes.as_ref(),
        );
        if let Some(fmt) = &options.instruction_format {
            params.push((
                "instructionFormat".to_string(),
                crate::util::enum_as_str(fmt),
            ));
        }
        add_option_ref(&mut params, "language", options.language.as_ref());

        // Toll
        add_option(&mut params, "tollVehicleType", options.toll_vehicle_type);
        add_option_ref(&mut params, "tollPass", options.toll_pass.as_ref());
        add_option_ref(&mut params, "currency", options.currency.as_ref());
        add_option_ref(&mut params, "driverCost", options.driver_cost.as_ref());
        add_option_ref(&mut params, "vehicleCost", options.vehicle_cost.as_ref());
        add_option_ref(
            &mut params,
            "vehicleCostOnFerry",
            options.vehicle_cost_on_ferry.as_ref(),
        );
        add_option_ref(
            &mut params,
            "costPerConsumptionUnit",
            options.cost_per_consumption_unit.as_ref(),
        );

        // Advanced
        add_option(&mut params, "maxSpeed", options.max_speed);
        add_option(&mut params, "alternatives", options.alternatives);
        add_option(&mut params, "truckVerified", options.truck_verified);
        add_option(
            &mut params,
            "ignoreWaypointVehicleRestriction",
            options.ignore_waypoint_vehicle_restriction,
        );
        add_option(
            &mut params,
            "adminTruckRestrictions",
            options.admin_truck_restrictions,
        );
        add_option(
            &mut params,
            "ignorePreferredRoutes",
            options.ignore_preferred_routes,
        );
        add_option_ref(
            &mut params,
            "excludeZoneTypes",
            options.exclude_zone_types.as_ref(),
        );
        add_option_ref(&mut params, "overlays", options.overlays.as_ref());
        add_option_ref(
            &mut params,
            "customRestrLimit",
            options.custom_restrict_limit.as_ref(),
        );
        add_option_ref(
            &mut params,
            "customAttributes",
            options.custom_attributes.as_ref(),
        );
        add_option_ref(
            &mut params,
            "customConsumptionDetails",
            options.custom_consumption_details.as_ref(),
        );
        add_option(&mut params, "timeout", options.timeout);
        add_option(&mut params, "drivingReport", options.driving_report);
        add_option_ref(
            &mut params,
            "ehorizonLimits",
            options.ehorizon_limits.as_ref(),
        );

        let url = format!("{}/match/routelinks", self.base_url);
        let builder = self
            .client
            .build_request(reqwest::Method::GET, &url)
            .query(&params);

        let here_res: HereMatchApiResponseWrapper = self.client.request_json(builder).await?;

        // Extract matched points and total distance from the API response
        let route = here_res.response.route.into_iter().next();
        let (matched_points, distance, duration) = match route {
            Some(r) => {
                let points = r
                    .waypoint
                    .into_iter()
                    .filter_map(|wp| {
                        let position = wp.mapped_position.or(wp.original_position)?;
                        Some(MatchedPoint {
                            coordinate: Coordinate::new(position.latitude, position.longitude)
                                .unwrap_or(Coordinate::ORIGIN),
                            confidence: wp.confidence_value,
                            road_name: None,
                        })
                    })
                    .collect();
                let total_length: f64 = r.leg.iter().map(|l| l.length).sum();
                let total_time: f64 = r.leg.iter().map(|l| l.travel_time).sum();
                (
                    points,
                    total_length,
                    if total_time > 0.0 {
                        Some(total_time)
                    } else {
                        None
                    },
                )
            }
            None => (vec![], 0.0, None),
        };

        Ok(TraceResponse {
            matched_points,
            distance,
            duration,
            raw: None,
        })
    }
}