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
pub mod types;

use crate::client::HereClient;
use async_trait::async_trait;
use everymap_core::domains::isoline::{
    IsolineOptions, IsolineProvider, IsolineResponse, IsolineResult,
};
use everymap_core::error::EveryMapResult;
use serde::{Deserialize, Serialize};
use std::sync::Arc;

pub use types::*;

const ISOLINE_BASE_URL: &str = "https://isoline.router.hereapi.com/v8";

/// Exhaustive options for HERE Isoline Routing API v8.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HereIsolineOptions {
    pub range_type: RangeType,
    pub transport_mode: IsolineTransportMode,
    pub routing_mode: IsolineRoutingMode,
    pub optimize_for: Option<OptimizeFor>,
    pub departure_time: Option<String>,
    pub arrival_time: Option<String>,
    pub avoid: Option<Vec<String>>,
    pub exclude: Option<Vec<String>>,
    pub shape: Option<String>,
    pub vehicle: Option<Vec<String>>,
    pub consumption_model: Option<ConsumptionModel>,
    pub ev: Option<Vec<String>>,
    pub fuel: Option<Vec<String>>,
    pub max_speed_on_segment: Option<Vec<String>>,
    pub taxi: Option<Vec<String>>,
    pub traffic: Option<TrafficMode>,
    pub billing_tag: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RangeType {
    #[default]
    Time,
    Distance,
    Consumption,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum IsolineTransportMode {
    #[default]
    Car,
    Truck,
    Pedestrian,
    Bicycle,
    Bus,
    PrivateBus,
    Scooter,
    Taxi,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum IsolineRoutingMode {
    #[default]
    Fast,
    Short,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OptimizeFor {
    Quality,
    Performance,
    Balanced,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConsumptionModel {
    Empirical,
    Physical,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TrafficMode {
    Live,
    Historical,
}

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

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

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

/// Wire format: `{"isolines": [{"range": {"type": "...", "value": N}, "polygons": [{"outer": "BFPol..."}]}]}`
#[derive(Debug, Deserialize)]
struct HereIsolineLegacyResponse {
    #[serde(default)]
    isolines: Vec<HereIsolineLegacy>,
}

#[derive(Debug, Deserialize)]
struct HereIsolineLegacy {
    #[serde(default)]
    range: Option<HereApiIsolineRange>,
    #[serde(default)]
    polygons: Vec<HereIsolinePolygon>,
    // Also support the old "polyline" field for backward compatibility
    #[serde(default)]
    polyline: Option<HereIsolinePolyline>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)] // Deserialize-only struct; fields only accessed via serde derive
struct HereApiIsolineRange {
    #[serde(default)]
    #[serde(rename = "type")]
    type_: Option<String>,
    #[serde(default)]
    value: Option<f64>,
}

#[derive(Debug, Deserialize)]
struct HereIsolinePolygon {
    #[serde(default)]
    outer: Option<String>,
}

#[derive(Debug, Deserialize)]
struct HereIsolinePolyline {
    #[serde(default)]
    outer: Option<String>,
}

impl From<HereIsolineLegacy> for IsolineResult {
    fn from(iso: HereIsolineLegacy) -> Self {
        // Try "polygons[].outer" first (v8 format), fall back to "polyline.outer"
        let encoded = iso
            .polygons
            .iter()
            .filter_map(|p| p.outer.as_ref())
            .next()
            .or_else(|| iso.polyline.as_ref().and_then(|p| p.outer.as_ref()));

        let polygon = encoded
            .map(|enc| {
                everymap_core::types::FlexiblePolyline::decode(enc).unwrap_or_else(|_| vec![])
            })
            .unwrap_or_default();

        let range = iso.range.and_then(|r| r.value);

        Self { range, polygon }
    }
}

/// Convert core `IsolineOptions` to HERE-specific `HereIsolineOptions`,
/// extracting common fields and parsing `provider_extra` for HERE-specific ones.
fn isoline_options_from_core(options: &IsolineOptions) -> HereIsolineOptions {
    let range_type = match options.range_type {
        Some(everymap_core::domains::isoline::RangeType::Distance) | None => RangeType::Distance,
        Some(everymap_core::domains::isoline::RangeType::Time) => RangeType::Time,
        Some(everymap_core::domains::isoline::RangeType::Consumption) => RangeType::Consumption,
    };

    let transport_mode = match options.transport_mode {
        Some(everymap_core::domains::routing::TransportMode::Car) | None => {
            IsolineTransportMode::Car
        }
        Some(everymap_core::domains::routing::TransportMode::Truck) => IsolineTransportMode::Truck,
        Some(everymap_core::domains::routing::TransportMode::Pedestrian) => {
            IsolineTransportMode::Pedestrian
        }
        Some(everymap_core::domains::routing::TransportMode::Bicycle) => {
            IsolineTransportMode::Bicycle
        }
        Some(everymap_core::domains::routing::TransportMode::Bus) => IsolineTransportMode::Bus,
        Some(everymap_core::domains::routing::TransportMode::Scooter) => {
            IsolineTransportMode::Scooter
        }
        Some(everymap_core::domains::routing::TransportMode::Taxi) => IsolineTransportMode::Taxi,
        Some(everymap_core::domains::routing::TransportMode::Unknown) => IsolineTransportMode::Car,
    };

    let mut here_options = HereIsolineOptions {
        range_type,
        transport_mode,
        departure_time: options.departure_time.as_ref().map(|dt| dt.to_string()),
        ..Default::default()
    };

    // Convert avoid types
    if !options.avoid.is_empty() {
        here_options.avoid = Some(
            options
                .avoid
                .iter()
                .map(|a| match a {
                    everymap_core::domains::routing::AvoidType::Tolls => "tolls".to_string(),
                    everymap_core::domains::routing::AvoidType::Ferries => "ferries".to_string(),
                    everymap_core::domains::routing::AvoidType::Tunnels => "tunnels".to_string(),
                    everymap_core::domains::routing::AvoidType::Highways => "highways".to_string(),
                    everymap_core::domains::routing::AvoidType::DirtRoads => {
                        "dirtRoads".to_string()
                    }
                })
                .collect(),
        );
    }

    // 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("routing_mode").and_then(|v| v.as_str()) {
                here_options.routing_mode = match v {
                    "short" => IsolineRoutingMode::Short,
                    _ => IsolineRoutingMode::Fast,
                };
            }
            if let Some(v) = obj.get("optimize_for") {
                here_options.optimize_for = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("arrival_time").and_then(|v| v.as_str()) {
                here_options.arrival_time = Some(v.to_string());
            }
            if let Some(v) = obj.get("exclude").and_then(|v| v.as_array()) {
                here_options.exclude = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("shape").and_then(|v| v.as_str()) {
                here_options.shape = Some(v.to_string());
            }
            if let Some(v) = obj.get("vehicle").and_then(|v| v.as_array()) {
                here_options.vehicle = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("consumption_model") {
                here_options.consumption_model = serde_json::from_value(v.clone()).ok();
            }
            if let Some(v) = obj.get("ev").and_then(|v| v.as_array()) {
                here_options.ev = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("fuel").and_then(|v| v.as_array()) {
                here_options.fuel = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("max_speed_on_segment").and_then(|v| v.as_array()) {
                here_options.max_speed_on_segment = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("taxi").and_then(|v| v.as_array()) {
                here_options.taxi = Some(
                    v.iter()
                        .filter_map(|i| i.as_str().map(String::from))
                        .collect(),
                );
            }
            if let Some(v) = obj.get("traffic").and_then(|v| v.as_str()) {
                here_options.traffic =
                    serde_json::from_value(serde_json::Value::String(v.to_string())).ok();
            }
            if let Some(v) = obj.get("billing_tag").and_then(|v| v.as_str()) {
                here_options.billing_tag = Some(v.to_string());
            }
        }
    }

    here_options
}

#[async_trait]
impl IsolineProvider for HereIsoline {
    async fn get_isoline(
        &self,
        center: &everymap_core::types::Coordinate,
        range: f64,
        options: &IsolineOptions,
    ) -> EveryMapResult<IsolineResponse> {
        let here_options = isoline_options_from_core(options);

        let range_type = match here_options.range_type {
            RangeType::Time => "time",
            RangeType::Distance => "distance",
            RangeType::Consumption => "consumption",
        };

        let transport = match here_options.transport_mode {
            IsolineTransportMode::Car => "car",
            IsolineTransportMode::Truck => "truck",
            IsolineTransportMode::Pedestrian => "pedestrian",
            IsolineTransportMode::Bicycle => "bicycle",
            IsolineTransportMode::Bus => "bus",
            IsolineTransportMode::PrivateBus => "privateBus",
            IsolineTransportMode::Scooter => "scooter",
            IsolineTransportMode::Taxi => "taxi",
        };

        let routing_mode = match here_options.routing_mode {
            IsolineRoutingMode::Fast => "fast",
            IsolineRoutingMode::Short => "short",
        };

        let mut params: Vec<(&str, String)> = vec![
            ("origin", format!("{},{}", center.lat, center.lng)),
            ("range[type]", range_type.to_string()),
            ("range[values]", range.to_string()),
            ("transportMode", transport.to_string()),
            ("routingMode", routing_mode.to_string()),
            ("return", "polyline".to_string()),
        ];

        if let Some(opt) = &here_options.optimize_for {
            let value = crate::util::enum_as_str(opt);
            params.push(("optimizeFor", value));
        }
        if let Some(departure_time) = &here_options.departure_time {
            params.push(("departureTime", departure_time.clone()));
        }
        if let Some(at) = &here_options.arrival_time {
            params.push(("arrivalTime", at.clone()));
        }
        if let Some(avoid) = &here_options.avoid {
            params.push(("avoid", avoid.join(",")));
        }
        if let Some(exclude) = &here_options.exclude {
            params.push(("exclude", exclude.join(",")));
        }
        if let Some(traffic) = &here_options.traffic {
            params.push(("traffic", crate::util::enum_as_str(traffic)));
        }
        if let Some(shape) = &here_options.shape {
            params.push(("shape", shape.clone()));
        }
        if let Some(vehicle) = &here_options.vehicle {
            params.push(("vehicle", vehicle.join(",")));
        }
        if let Some(consumption_model) = &here_options.consumption_model {
            params.push((
                "consumptionModel",
                crate::util::enum_as_str(consumption_model),
            ));
        }
        if let Some(ev) = &here_options.ev {
            params.push(("ev", ev.join(",")));
        }
        if let Some(fuel) = &here_options.fuel {
            params.push(("fuel", fuel.join(",")));
        }
        if let Some(max_speed_on_segment) = &here_options.max_speed_on_segment {
            params.push(("maxSpeedOnSegment", max_speed_on_segment.join(",")));
        }
        if let Some(taxi) = &here_options.taxi {
            params.push(("taxi", taxi.join(",")));
        }
        if let Some(billing_tag) = &here_options.billing_tag {
            params.push(("billingTag", billing_tag.clone()));
        }

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

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

        let isolines: Vec<IsolineResult> = here_res
            .isolines
            .into_iter()
            .map(IsolineResult::from)
            .collect();

        Ok(IsolineResponse {
            isolines,
            raw: None,
        })
    }
}