osrm_client/data/
common.rs

1//! This module comprises a representation of the data that is shared accross
2//! all OSRM services.
3
4use displaythis::Display;
5use serde::{Serialize, Deserialize};
6
7
8/// Mode of transportation
9#[derive(Debug, Display, Clone, Copy, Serialize, Deserialize)]
10pub enum TransportationMode {
11    /// Travelling by car
12    #[display("car")]
13    #[serde(rename="car")]
14    Car, 
15    /// Travelling by bike
16    #[display("bike")]
17    #[serde(rename="bike")]
18    Bike, 
19    /// Travelling on bare foot
20    #[display("foot")]
21    #[serde(rename="foot")]
22    Foot,
23}
24
25/// Route geometry format (influences overview and per step)
26#[derive(Debug, Display, Clone, Copy, Serialize, Deserialize)]
27pub enum Geometries {
28    #[display("polyline")]
29    #[serde(rename="polyline")]
30    Polyline, 
31    #[display("polyline6")]
32    #[serde(rename="polyline6")]
33    Polyline6, 
34    #[display("geojson")]
35    #[serde(rename="geojson")]
36    GeoJson,
37}
38
39/// The location of a point anywhere on earth. The order of the fields is
40/// longitude, latitude
41#[derive(Debug, Display, Clone, Copy, Serialize, Deserialize)]
42#[display("{longitude},{latitude}")]
43pub struct Location{
44    pub longitude: f32, 
45    pub latitude: f32
46}
47impl Location {
48    pub fn new(longitude: f32, latitude: f32) -> Self {
49        Self { longitude, latitude }
50    }
51}
52
53/// Most services are quite flexible wrt the coordinates they accept:
54/// it can either be a single coord, a sequence of coord separated by semicolon,
55/// or a polyline (follows Google polyline format) or polyline with precision of 6.
56#[derive(Debug, Clone)]
57pub enum Coordinates {
58    /// One single coordinate
59    Single(Location),
60    /// A sequence of coordinates in the longitude, latitude form
61    Multi(Vec<Location>),
62    /// A polyline formatted according to Google polyline format (precision 5)
63    Polyline(String),
64    /// A polyline formatted according to Google polyline format (precision 6)
65    Polyline6(String),
66}
67impl std::fmt::Display for Coordinates {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        match self {
70            Self::Single(c) => write!(f, "{c}"),
71            Self::Multi(coord) => {
72                for (i, c) in coord.iter().enumerate() {
73                    if i == 0 {
74                        write!(f, "{c}")?;
75                    } else {
76                        write!(f, ";{c}")?;
77                    }
78                }
79                Ok(())
80            },
81            Self::Polyline(s) => write!(f, "polyline({s})"),
82            Self::Polyline6(s) => write!(f, "polyline6({s})"),
83        }
84    }
85}
86
87/// Hint from previous request to derive position in street network (base64 encoded)
88#[derive(Debug, Display, Clone, Serialize, Deserialize)]
89#[display("{0}")]
90pub struct Hint(String);
91
92/// Object used to describe waypoint on a route
93#[derive(Debug, Clone, Serialize, Deserialize)]
94pub struct Waypoint {
95    /// Name of the street the coordinate snapped to
96    pub name: String,
97    /// the [longitude, latitude] pair of the snapped coordinate
98    pub location: Location,
99    /// The distance, in metres, from the input coordinate to the snapped coordinate
100    pub distance: f32, 
101    /// Unique internal identifier of the segment (ephemeral, not constant over data 
102    /// updates) This can be used on subsequent request to significantly speed up the 
103    /// query and to connect multiple services. E.g. you can use the hint value obtained 
104    /// by the nearest query as hint values for route inputs.
105    pub hint: Hint,
106    /// Array of OpenStreetMap node ids
107    pub nodes: Option<Vec<usize>>,
108}
109
110/// An intersection gives a full representation of any cross-way the path passes bay. 
111/// For every step, the very first intersection (intersections[0]) corresponds to the 
112/// location of the StepManeuver. Further intersections are listed for every cross-way 
113/// until the next turn instruction.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Intersection {
116    /// the [longitude, latitude] pair describing the location of the turn.
117    pub location: Location,
118    /// A list of bearing values (e.g. [0,90,180,270]) that are available at the intersection.
119    /// The bearings describe all available roads at the intersection. Values are between 
120    /// 0-359 (0=true north)
121    pub bearings: Vec<u16>,
122    /// An array of strings signifying the classes (as specified in the profile) of the road
123    /// exiting the intersection
124    pub classes:  Vec<String>,
125    /// A list of entry flags, corresponding in a 1:1 relationship to the bearings. A value 
126    /// of true indicates that the respective road could be entered on a valid route. 
127    /// false indicates that the turn onto the respective road would violate a restriction.
128    pub entry: Vec<bool>,
129    /// index into bearings/entry array. Used to calculate the bearing just before the turn.
130    /// Namely, the clockwise angle from true north to the direction of travel immediately 
131    /// before the maneuver/passing the intersection. Bearings are given relative to the 
132    /// intersection. To get the bearing in the direction of driving, the bearing has to be 
133    /// rotated by a value of 180. The value is not supplied for depart maneuvers.
134    pub in_index: usize,
135    /// index into the bearings/entry array. Used to extract the bearing just after the turn. 
136    /// Namely, The clockwise angle from true north to the direction of travel immediately 
137    /// after the maneuver/passing the intersection. The value is not supplied for arrive 
138    /// maneuvers.
139    pub out_index: usize,
140    /// Array of Lane objects that denote the available turn lanes at the intersection. 
141    /// If no lane information is available for an intersection, the lanes property will not 
142    /// be present.
143    pub lanes: Vec<Lane>
144}
145
146/// A Lane represents a turn lane at the corresponding turn location.
147#[derive(Debug, Clone, Serialize, Deserialize)]
148pub struct Lane {
149    /// A indication (e.g. marking on the road) specifying the turn lane. A road can have multiple 
150    /// indications (e.g. an arrow pointing straight and left). The indications are given in an 
151    /// array, each containing one of the following types. Further indications might be added on 
152    /// without an API version change.
153    /// 
154    /// ## Documented Values:
155    /// * none           -> No dedicated indication is shown.
156    /// * uturn          -> An indication signaling the possibility to reverse (i.e. fully bend arrow).
157    /// * sharp right    -> An indication indicating a sharp right turn (i.e. strongly bend arrow).
158    /// * right          -> An indication indicating a right turn (i.e. bend arrow).
159    /// * slight right   -> An indication indicating a slight right turn (i.e. slightly bend arrow).
160    /// * straight       -> No dedicated indication is shown (i.e. straight arrow).
161    /// * slight left    -> An indication indicating a slight left turn (i.e. slightly bend arrow).
162    /// * left           -> An indication indicating a left turn (i.e. bend arrow).
163    /// * sharp left     -> An indication indicating a sharp left turn (i.e. strongly bend arrow).
164    indications: Vec<DirectionChange>,
165    /// a boolean flag indicating whether the lane is a valid choice in the current maneuver
166    valid: bool,
167}
168
169/// An indication of a change of direction
170#[derive(Debug, Display, Clone, Serialize, Deserialize)]
171pub enum DirectionChange {
172    /// An indication signaling the possibility to reverse (i.e. fully bend arrow).
173    #[display("uturn")]
174    #[serde(rename="uturn")]
175    Uturn,
176    /// An indication indicating a sharp right turn (i.e. strongly bend arrow).
177    #[display("sharp right")]
178    #[serde(rename="sharp right")]
179    SharpRight,
180    /// An indication indicating a right turn (i.e. bend arrow).
181    #[display("right")]
182    #[serde(rename="right")]
183    Right,
184    /// An indication indicating a slight right turn (i.e. slightly bend arrow).
185    #[display("slight right")]
186    #[serde(rename="slight right")]
187    SlightRight,
188    /// No dedicated indication is shown (i.e. straight arrow).
189    #[display("straight")]
190    #[serde(rename="straight")]
191    Straight,
192    /// An indication indicating a slight left turn (i.e. slightly bend arrow).
193    #[display("slight left")]
194    #[serde(rename="slight left")]
195    SlightLeft,
196    /// An indication indicating a left turn (i.e. bend arrow).
197    #[display("left")]
198    #[serde(rename="left")]
199    Left,
200    /// An indication indicating a sharp left turn (i.e. strongly bend arrow).
201    #[display("sharp left")]
202    #[serde(rename="sharp left")]
203    SharpLeft,
204}
205
206/// type A string indicating the type of maneuver. new identifiers might be introduced 
207/// without API change Types unknown to the client should be handled like the turn type, 
208/// the existence of correct modifier values is guranteed
209#[derive(Debug, Display, Clone, Serialize, Deserialize)]
210pub enum ManeuverType {
211    /// a basic turn into direction of the modifier
212    #[display("turn")]
213    #[serde(rename="turn")]
214    Turn,
215    /// no turn is taken/possible, but the road name changes
216    #[display("new name")]
217    #[serde(rename="new name")]
218    NewName,
219    /// indicates the departure of the leg
220    #[display("depart")]
221    #[serde(rename="depart")]
222    Depart,
223    /// indicates the destination of the leg
224    #[display("arrive")]
225    #[serde(rename="arrive")]
226    Arrive,
227    /// merge onto a street (e.g. getting on the highway from a ramp, the modifier specifies 
228    /// the direction of the merge )
229    #[display("merge")]
230    #[serde(rename="merge")]
231    Merge, 
232    /// Deprecated . Replaced by on_ramp and off_ramp .
233    #[display("ramp")]
234    #[serde(rename="ramp")]
235    Ramp,
236    /// take a ramp to enter a highway (direction given my modifier )
237    #[display("on ramp")]
238    #[serde(rename="on ramp")]
239    OnRamp,
240    /// take a ramp to exit a highway (direction given my modifier )
241    #[display("off ramp")]
242    #[serde(rename="off ramp")]
243    OffRamp,
244    /// take the left/right side at a fork depending on modifier
245    #[display("fork")]
246    #[serde(rename="fork")]
247    Fork,
248    /// road ends in a T intersection turn in direction of modifier
249    #[display("end of road")]
250    #[serde(rename="end of road")]
251    EnfOfRoad,
252    /// Deprecated replaced by lanes on all intersection entries
253    #[display("use lane")]
254    #[serde(rename="use lane")]
255    UseLane,
256    /// Turn in direction of modifier to stay on the same road
257    #[display("continue")]
258    #[serde(rename="continue")]
259    Continue,
260    /// traverse roundabout, if the route leaves the roundabout there will be
261    /// an additional property exit for exit counting. The modifier specifies 
262    /// the direction of entering the roundabout.
263    #[display("roundabout")]
264    #[serde(rename="roundabout")]
265    Roundabout,
266    /// a traffic circle. While very similar to a larger version of a roundabout, 
267    /// it does not necessarily follow roundabout rules for right of way. It can
268    /// offer rotary_name and/or rotary_pronunciation parameters (located in the 
269    /// RouteStep object) in addition to the exit parameter (located on the StepManeuver 
270    /// object).
271    #[display("rotary")]
272    #[serde(rename="rotary")]
273    Rotary,
274    /// Describes a turn at a small roundabout that should be treated as normal turn. 
275    /// The modifier indicates the turn direciton. 
276    /// Example instruction: At the roundabout turn left .
277    #[display("roundabout turn")]
278    #[serde(rename="roundabout turn")]
279    RoundaboutTurn,
280    /// not an actual turn but a change in the driving conditions. 
281    /// For example the travel mode or classes. If the road takes a turn itself, 
282    /// the modifier describes the direction
283    #[display("notification")]
284    #[serde(rename="notification")]
285    Notification,
286    /// Describes a maneuver exiting a roundabout (usually preceeded by a roundabout instruction)
287    #[display("exit roundabout")]
288    #[serde(rename="exit roundabout")]
289    ExitRoundabout,
290    /// Describes the maneuver exiting a rotary (large named roundabout)
291    #[display("exit rotary")]
292    #[serde(rename="exit rotary")]
293    ExitRotary,
294}
295
296/// A maneuver that must be performed to follow a route
297#[derive(Debug, Clone, Serialize, Deserialize)]
298pub struct StepManeuver {
299    /// A [longitude, latitude] pair describing the location of the turn.
300    pub location: Location,
301    /// The clockwise angle from true north to the direction of travel immediately 
302    /// before the maneuver. Range 0-359.
303    pub bearing_before: u16,
304    /// The clockwise angle from true north to the direction of travel immediately 
305    /// after the maneuver. Range 0-359.
306    pub bearing_aftter: u16,
307    /// A string indicating the type of maneuver. 
308    /// **new identifiers might be introduced without API change** 
309    /// Types unknown to the client should be handled like the turn type, the existence 
310    /// of correct modifier values is guranteed.
311    #[serde(rename="type")]
312    pub maneuver_type: ManeuverType,
313    /// An optional string indicating the direction change of the maneuver.
314    /// 
315    /// The list of turns without a modifier is limited to: depart/arrive. 
316    /// If the source/target location is close enough to the depart/arrive location, 
317    /// no modifier will be given. The meaning depends on the type property.
318    /// 
319    /// ## Examples
320    /// * turn -> modifier indicates the change in direction accomplished by the turn
321    /// * depart / arrive -> modifier indicates the position of departure and arrival 
322    ///           point in relation to the current direction of travel.
323    pub modifier: Option<DirectionChange>,
324    /// An optional integer indicating number of the exit to take. The property exists 
325    /// for the roundabout / rotary property: Number of the roundabout exit to take. 
326    /// If exit is undefined the destination is on the roundabout
327    pub exit: Option<u8>,
328}
329
330/// A step consists of a maneuver such as a turn or merge, followed by a distance of 
331/// travel along a single way to the subsequent step.
332#[derive(Debug, Clone, Serialize, Deserialize)]
333pub struct RouteStep { 
334    /// The distance of travel from the maneuver to the subsequent step, in meters.
335    pub distance: f32,
336    /// The estimated travel time, in seconds
337    pub duration: f32,
338    /// The unsimplified geometry of the route segment, depending on the geometries parameter.
339    pub geometry: Geometry,
340    /// The calculated weight of the step.
341    pub weight: f32,
342    /// The name of the way along which travel proceeds.
343    pub name: String,
344    /// A reference number or code for the way. Optionally included, 
345    /// if ref data is available for the given way.
346    #[serde(rename="ref")]
347    pub reference: Option<String>,
348    /// A string containing an IPA phonetic transcription indicating how to pronounce the name in 
349    /// the name property. This property is omitted if pronunciation data is unavailable for the step.
350    pub pronunciation: Option<String>,
351    // /// The destinations of the way. Will be undefined if there are no destinations
352    // pub destinations: Vec< WHAT_SHOULD_I_USE_HERE >,
353    // /// The exit numbers or names of the way. Will be undefined if there are no exit numbers or names
354    // pub exits: Vec< WHAT_SHOULD_I_USE_HERE >,
355    
356    /// A string signifying the mode of transportation
357    pub mode: TransportationMode,
358    /// A StepManeuver object representing the maneuver
359    pub maneuver: StepManeuver,
360    /// A list of Intersection objects that are passed along the segment, the very first belonging 
361    /// to the StepManeuver
362    pub intersections: Vec<Intersection>,
363    /// The name for the rotary. Optionally included, if the step is a rotary and a rotary name is available
364    pub rotary_name: Option<String>,
365    /// The pronunciation hint of the rotary name. Optionally included, if the step is a rotary and 
366    /// a rotary pronunciation is available.
367    pub rotary_pronunciation: Option<String>,
368    /// The legal driving side at the location for this step. Either left or right
369    pub driving_side: Option<DrivingSide>,
370}
371
372/// The legal driving side at a location
373#[derive(Debug, Display, Clone, Serialize, Deserialize)]
374pub enum DrivingSide {
375    /// a basic turn into direction of the modifier
376    #[display("left")]
377    #[serde(rename="left")]
378    Left,
379    #[display("right")]
380    #[serde(rename="right")]
381    Right,
382}
383
384/// Annotation of the whole route leg with fine-grained information about each segment or node id.
385#[derive(Debug, Clone, Serialize, Deserialize)]
386pub struct Annotation {
387    /// The distance, in metres, between each pair of coordinates
388    pub distance: f32,
389    /// The duration between each pair of coordinates, in seconds. Does not include the 
390    /// duration of any turns
391    pub duration: f32,
392    /// The index of the datasource for the speed between each pair of coordinates. 0 is the default 
393    /// profile, other values are supplied via --segment-speed-file to osrm-contract or osrm-customize. 
394    /// String-like names are in the metadata.datasource_names array.
395    pub datasources: Vec<usize>,
396    /// The OSM node ID for each coordinate along the route, excluding the first/last user-supplied
397    /// coordinates
398    pub nodes: Option<Vec<usize>>,
399    /// The weights between each pair of coordinates. Does not include any turn costs
400    pub weight: Vec<f32>,
401    /// Convenience field, calculation of distance / duration rounded to one decimal place
402    pub speed: f32,
403    /// Metadata related to other annotations
404    pub metadata: AnnotationMetaData,
405}
406/// Some meta-data attached to route annotations
407#[derive(Debug, Clone, Serialize, Deserialize)]
408pub struct AnnotationMetaData {
409    /// The names of the datasources used for the speed between each pair of coordinates. lua profile 
410    /// is the default profile, other values arethe filenames supplied via --segment-speed-file to 
411    /// osrm-contract or osrm-customize
412    pub datasource_names: Option<Vec<String>>,
413}
414/// Represents a route between two waypoints.
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct RouteLeg {
417    /// The distance traveled by this route leg, in float meters.
418    pub distance: f32,
419    /// The estimated travel time, in of seconds
420    pub duration: f32,
421    /// The calculated weight of the route leg.
422    pub weight: f32,
423    /// Summary of the route taken as string. Depends on the summary parameter
424    /// * true -> Names of the two major roads used. Can be empty if route is too short
425    /// * false-> empty string
426    pub summary: String,
427    /// Depends on the steps parameter.
428    /// * true -> array of RouteStep objects describing the turn-by-turn instructions
429    /// * false-> empty array
430    pub steps: Vec<RouteStep>,
431    /// Additional details about each coordinate along the route geometry
432    /// * true -> An Annotation object containing node ids, durations, distances and weights.
433    /// * false-> undefined (none)
434    pub annotation: Option<Annotation>
435}
436/// Represents a route through (potentially multiple) waypoints.
437#[derive(Debug, Clone, Serialize, Deserialize)]
438pub struct Route {
439    /// The distance traveled by this route, in meters.
440    pub distance: f32,
441    /// The estimated travel time, in seconds
442    pub duration: f32,
443    /// The whole geometry of the route value depending on overview parameter, format depending on 
444    /// the geometries parameter. See RouteStep's geometry property for a parameter documentation.
445    pub geometry: Geometry,
446    /// The calculated weight of the route.
447    pub weight: f32,
448    /// The name of the weight profile used during extraction phas
449    pub weight_name: String,
450    /// The legs between the given waypoints, an array of RouteLeg objects.
451    pub legs: Vec<RouteLeg>,
452}
453
454/// Represents a geometry which can either be encoded with polyline of polyline6
455/// or explicit in the form of a geojson
456#[derive(Debug, Clone, Serialize, Deserialize)]
457#[serde(untagged)]
458pub enum Geometry {
459    /// When the geometry is encoded with polyline or polyline6
460    Encoded(String),
461    /// When the geometry is explicitly detailed
462    Explicit(GeoJsonGeometry)
463}
464
465/// GeoJSON[1] is an open standard format designed for representing simple geographical features, 
466/// along with their non-spatial attributes. It is based on the JSON format.
467/// 
468/// The features include points (therefore addresses and locations), line strings (therefore streets, 
469/// highways and boundaries), polygons (countries, provinces, tracts of land), and multi-part 
470/// collections of these types. GeoJSON features need not represent entities of the physical 
471/// world only; mobile routing and navigation apps, for example, might describe their service 
472/// coverage using GeoJSON.[2]
473///
474/// The GeoJSON format differs from other GIS standards in that it was written and is maintained 
475/// not by a formal standards organization, but by an Internet working group of developers.[3] 
476/// 
477/// ## Geometries
478/// Points are [x, y] or [x, y, z]. They may be [longitude, latitude] or [eastings, northings]. 
479/// Elevation is an optional third number. They are decimal numbers. [6]
480/// For example, London (51.5074° North, 0.1278° West) is [-0.1278, 51.5074] 
481/// 
482/// (Ref: https://en.wikipedia.org/wiki/GeoJSON#Geometries)
483/// 
484#[derive(Debug, Clone, Serialize, Deserialize)]
485#[serde(tag="type")]
486pub enum GeoJsonGeometry {
487    Point { coordinates: GeoJsonPoint },
488    LineString { coordinates: Vec<GeoJsonPoint> },
489    Polygon { coordinates: Vec<Vec<GeoJsonPoint>> },
490    MultiPoint { coordinates: Vec<GeoJsonPoint> },
491    MultiLineString { coordinates: Vec<Vec<GeoJsonPoint>> },
492    MultiPolygon { coordinates: Vec<Vec<Vec<GeoJsonPoint>>> },
493}
494
495/// Points are [x, y] or [x, y, z]. They may be [longitude, latitude] or [eastings, northings]. 
496/// Elevation is an optional third number. They are decimal numbers. [6]
497/// For example, London (51.5074° North, 0.1278° West) is [-0.1278, 51.5074] 
498#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
499#[serde(untagged)]
500pub enum GeoJsonPoint {
501    Regular([f32; 2]),
502    Elevated([f32; 3]),
503}
504impl GeoJsonPoint {
505    pub fn location(self) -> Location {
506        match self {
507            GeoJsonPoint::Regular(x)  => Location { longitude: x[0], latitude: x[1] },
508            GeoJsonPoint::Elevated(x) => Location { longitude: x[0], latitude: x[1] },
509        }
510    }
511    pub fn elevation(self) -> Option<f32> {
512        match self {
513            GeoJsonPoint::Regular(_)  => None,
514            GeoJsonPoint::Elevated(x) => Some(x[2]),
515        }
516    }
517    pub fn coordinates(&self) -> &[f32] {
518        match self {
519            GeoJsonPoint::Regular(x)  => x,
520            GeoJsonPoint::Elevated(x) => x,
521        }
522    }
523}
524impl From<Location> for GeoJsonPoint {
525    fn from(Location { longitude, latitude }: Location) -> Self {
526        Self::Regular([longitude, latitude])
527    }
528}