Skip to main content

map_expressions/
lib.rs

1//! Deterministic map-label selection and collision handling.
2//!
3//! The crate turns already-supplied geographic features into normalized screen
4//! positions. It does not download map data, choose a legal data license, or
5//! replace a full cartographic projection engine.
6
7#![forbid(unsafe_code)]
8#![warn(missing_docs)]
9
10use std::cmp::Reverse;
11use std::collections::BTreeMap;
12use std::error::Error;
13use std::fmt;
14
15/// Official GSI explanation of vector-tile map expression.
16pub const GSI_VECTOR_TILE_URL: &str = "https://maps.gsi.go.jp/development/vt_expt.html";
17
18/// Official GSI Maps Vector viewer.
19pub const GSI_MAPS_VECTOR_URL: &str = "https://maps.gsi.go.jp/vector/";
20
21/// A validated WGS84-style latitude and longitude pair in degrees.
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct GeoPoint {
24    latitude: f64,
25    longitude: f64,
26}
27
28impl GeoPoint {
29    /// Creates a point with latitude in `[-90, 90]` and longitude in `[-180, 180]`.
30    pub fn new(latitude: f64, longitude: f64) -> Result<Self, MapError> {
31        if !latitude.is_finite() || !(-90.0..=90.0).contains(&latitude) {
32            return Err(MapError::InvalidLatitude);
33        }
34        if !longitude.is_finite() || !(-180.0..=180.0).contains(&longitude) {
35            return Err(MapError::InvalidLongitude);
36        }
37        Ok(Self {
38            latitude,
39            longitude,
40        })
41    }
42
43    /// Returns latitude in degrees.
44    pub const fn latitude(self) -> f64 {
45        self.latitude
46    }
47
48    /// Returns longitude in degrees.
49    pub const fn longitude(self) -> f64 {
50        self.longitude
51    }
52}
53
54/// Geographic area displayed by a map, including antimeridian-wrapping areas.
55#[derive(Debug, Clone, Copy, PartialEq)]
56pub struct Viewport {
57    south: f64,
58    west: f64,
59    north: f64,
60    east: f64,
61}
62
63impl Viewport {
64    /// Creates a viewport. `west > east` represents wrapping across ±180°.
65    pub fn new(south: f64, west: f64, north: f64, east: f64) -> Result<Self, MapError> {
66        GeoPoint::new(south, west)?;
67        GeoPoint::new(north, east)?;
68        if south >= north {
69            return Err(MapError::InvalidViewport);
70        }
71        Ok(Self {
72            south,
73            west,
74            north,
75            east,
76        })
77    }
78
79    /// Returns true when the point is inside this viewport.
80    pub fn contains(self, point: GeoPoint) -> bool {
81        let latitude_inside = (self.south..=self.north).contains(&point.latitude);
82        let longitude_inside = if self.west <= self.east {
83            (self.west..=self.east).contains(&point.longitude)
84        } else {
85            point.longitude >= self.west || point.longitude <= self.east
86        };
87        latitude_inside && longitude_inside
88    }
89
90    /// Projects a contained point to normalized screen coordinates.
91    pub fn project(self, point: GeoPoint) -> Option<ScreenPoint> {
92        if !self.contains(point) {
93            return None;
94        }
95        let width = if self.west <= self.east {
96            self.east - self.west
97        } else {
98            (180.0 - self.west) + (self.east + 180.0)
99        };
100        let offset = if self.west <= self.east || point.longitude >= self.west {
101            point.longitude - self.west
102        } else {
103            (180.0 - self.west) + (point.longitude + 180.0)
104        };
105        let x = if width == 0.0 { 0.5 } else { offset / width };
106        let y = (self.north - point.latitude) / (self.north - self.south);
107        Some(ScreenPoint { x, y })
108    }
109}
110
111/// Normalized screen coordinate with `(0, 0)` at the top left.
112#[derive(Debug, Clone, Copy, PartialEq)]
113pub struct ScreenPoint {
114    x: f64,
115    y: f64,
116}
117
118impl ScreenPoint {
119    /// Returns normalized horizontal position.
120    pub const fn x(self) -> f64 {
121        self.x
122    }
123
124    /// Returns normalized vertical position.
125    pub const fn y(self) -> f64 {
126        self.y
127    }
128}
129
130/// Localized label text with explicit fallback.
131#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct LocalizedLabel {
133    values: BTreeMap<String, String>,
134}
135
136impl LocalizedLabel {
137    /// Creates an empty localized label.
138    pub fn new() -> Self {
139        Self::default()
140    }
141
142    /// Adds or replaces a non-blank language and label value.
143    pub fn insert(
144        &mut self,
145        language: impl Into<String>,
146        value: impl Into<String>,
147    ) -> Result<(), MapError> {
148        let language = language.into();
149        let value = value.into();
150        if language.trim().is_empty() || value.trim().is_empty() {
151            return Err(MapError::EmptyLabelValue);
152        }
153        self.values.insert(language, value);
154        Ok(())
155    }
156
157    /// Returns requested text, then fallback text when unavailable.
158    pub fn get_with_fallback(&self, requested: &str, fallback: &str) -> Option<&str> {
159        self.values
160            .get(requested)
161            .or_else(|| self.values.get(fallback))
162            .map(String::as_str)
163    }
164}
165
166/// Relative importance used when labels collide.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
168pub enum LabelPriority {
169    /// Optional background context.
170    Background,
171    /// Local place information.
172    Local,
173    /// A major landmark.
174    Landmark,
175    /// A transport interchange or route anchor.
176    Transit,
177    /// Time-sensitive safety information.
178    Emergency,
179}
180
181/// A labeled geographic feature and its visible zoom interval.
182#[derive(Debug, Clone, PartialEq)]
183pub struct MapFeature {
184    id: String,
185    point: GeoPoint,
186    label: LocalizedLabel,
187    priority: LabelPriority,
188    min_zoom: u8,
189    max_zoom: u8,
190}
191
192impl MapFeature {
193    /// Creates a feature visible between the inclusive zoom limits.
194    pub fn new(
195        id: impl Into<String>,
196        point: GeoPoint,
197        label: LocalizedLabel,
198        priority: LabelPriority,
199        min_zoom: u8,
200        max_zoom: u8,
201    ) -> Result<Self, MapError> {
202        let id = id.into();
203        if id.trim().is_empty() {
204            return Err(MapError::EmptyFeatureId);
205        }
206        if label.values.is_empty() {
207            return Err(MapError::MissingLabel);
208        }
209        if min_zoom > max_zoom {
210            return Err(MapError::InvalidZoomRange);
211        }
212        Ok(Self {
213            id,
214            point,
215            label,
216            priority,
217            min_zoom,
218            max_zoom,
219        })
220    }
221}
222
223/// A label selected for display.
224#[derive(Debug, Clone, PartialEq)]
225pub struct PlacedLabel {
226    /// Stable feature identifier.
227    pub id: String,
228    /// Localized visible text.
229    pub text: String,
230    /// Normalized display position.
231    pub position: ScreenPoint,
232    /// Priority used during placement.
233    pub priority: LabelPriority,
234}
235
236/// Deterministic label-layout policy.
237#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
238pub struct MapDisplay;
239
240impl MapDisplay {
241    /// Places visible labels by priority while suppressing nearby collisions.
242    ///
243    /// `minimum_gap` is Euclidean distance in normalized screen coordinates and
244    /// must be finite and non-negative.
245    pub fn layout(
246        features: &[MapFeature],
247        viewport: Viewport,
248        zoom: u8,
249        requested_language: &str,
250        fallback_language: &str,
251        minimum_gap: f64,
252    ) -> Result<Vec<PlacedLabel>, MapError> {
253        if !minimum_gap.is_finite() || minimum_gap < 0.0 {
254            return Err(MapError::InvalidMinimumGap);
255        }
256
257        let mut candidates: Vec<_> = features
258            .iter()
259            .filter(|feature| (feature.min_zoom..=feature.max_zoom).contains(&zoom))
260            .filter_map(|feature| {
261                let position = viewport.project(feature.point)?;
262                let text = feature
263                    .label
264                    .get_with_fallback(requested_language, fallback_language)?;
265                Some((feature, position, text))
266            })
267            .collect();
268        candidates.sort_by_key(|(feature, _, _)| (Reverse(feature.priority), feature.id.as_str()));
269
270        let mut placed: Vec<PlacedLabel> = Vec::new();
271        for (feature, position, text) in candidates {
272            let collides = placed.iter().any(|existing| {
273                let dx = existing.position.x - position.x;
274                let dy = existing.position.y - position.y;
275                dx.hypot(dy) < minimum_gap
276            });
277            if !collides {
278                placed.push(PlacedLabel {
279                    id: feature.id.clone(),
280                    text: text.to_owned(),
281                    position,
282                    priority: feature.priority,
283                });
284            }
285        }
286        Ok(placed)
287    }
288}
289
290/// Invalid map-display input.
291#[derive(Debug, Clone, Copy, PartialEq, Eq)]
292pub enum MapError {
293    /// Latitude was non-finite or outside `[-90, 90]`.
294    InvalidLatitude,
295    /// Longitude was non-finite or outside `[-180, 180]`.
296    InvalidLongitude,
297    /// Viewport had no positive latitude span.
298    InvalidViewport,
299    /// Language or label text was blank.
300    EmptyLabelValue,
301    /// Feature identifier was blank.
302    EmptyFeatureId,
303    /// Feature had no localized label.
304    MissingLabel,
305    /// Minimum zoom exceeded maximum zoom.
306    InvalidZoomRange,
307    /// Collision gap was negative or non-finite.
308    InvalidMinimumGap,
309}
310
311impl fmt::Display for MapError {
312    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
313        let message = match self {
314            Self::InvalidLatitude => "latitude must be finite and within -90 to 90",
315            Self::InvalidLongitude => "longitude must be finite and within -180 to 180",
316            Self::InvalidViewport => "viewport must have a positive latitude span",
317            Self::EmptyLabelValue => "label language and value must not be blank",
318            Self::EmptyFeatureId => "feature id must not be blank",
319            Self::MissingLabel => "feature must have at least one label",
320            Self::InvalidZoomRange => "minimum zoom must not exceed maximum zoom",
321            Self::InvalidMinimumGap => "minimum gap must be finite and non-negative",
322        };
323        formatter.write_str(message)
324    }
325}
326
327impl Error for MapError {}
328
329#[cfg(test)]
330mod tests {
331    use super::*;
332
333    fn label(text: &str) -> LocalizedLabel {
334        let mut label = LocalizedLabel::new();
335        label.insert("ja", text).unwrap();
336        label
337    }
338
339    fn feature(id: &str, longitude: f64, priority: LabelPriority) -> MapFeature {
340        MapFeature::new(
341            id,
342            GeoPoint::new(0.0, longitude).unwrap(),
343            label(id),
344            priority,
345            0,
346            20,
347        )
348        .unwrap()
349    }
350
351    #[test]
352    fn invalid_coordinates_are_rejected() {
353        assert_eq!(GeoPoint::new(91.0, 0.0), Err(MapError::InvalidLatitude));
354        assert_eq!(
355            GeoPoint::new(0.0, f64::NAN),
356            Err(MapError::InvalidLongitude)
357        );
358    }
359
360    #[test]
361    fn antimeridian_viewport_projects_both_sides() {
362        let viewport = Viewport::new(-10.0, 170.0, 10.0, -170.0).unwrap();
363        let west_side = viewport
364            .project(GeoPoint::new(0.0, 175.0).unwrap())
365            .unwrap();
366        let east_side = viewport
367            .project(GeoPoint::new(0.0, -175.0).unwrap())
368            .unwrap();
369        assert!((west_side.x() - 0.25).abs() < 1e-12);
370        assert!((east_side.x() - 0.75).abs() < 1e-12);
371    }
372
373    #[test]
374    fn higher_priority_label_wins_collision() {
375        let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
376        let features = [
377            feature("local", 0.0, LabelPriority::Local),
378            feature("emergency", 0.01, LabelPriority::Emergency),
379        ];
380        let placed = MapDisplay::layout(&features, viewport, 10, "ja", "ja", 0.1).unwrap();
381        assert_eq!(placed.len(), 1);
382        assert_eq!(placed[0].id, "emergency");
383    }
384
385    #[test]
386    fn zoom_and_language_filter_are_applied() {
387        let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
388        let mut localized = label("駅");
389        localized.insert("en", "Station").unwrap();
390        let feature = MapFeature::new(
391            "station",
392            GeoPoint::new(0.0, 0.0).unwrap(),
393            localized,
394            LabelPriority::Transit,
395            8,
396            12,
397        )
398        .unwrap();
399        assert!(
400            MapDisplay::layout(std::slice::from_ref(&feature), viewport, 7, "en", "ja", 0.0)
401                .unwrap()
402                .is_empty()
403        );
404        let placed = MapDisplay::layout(&[feature], viewport, 10, "en", "ja", 0.0).unwrap();
405        assert_eq!(placed[0].text, "Station");
406    }
407
408    #[test]
409    fn invalid_layout_gap_is_rejected() {
410        let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
411        assert_eq!(
412            MapDisplay::layout(&[], viewport, 1, "ja", "ja", -0.1),
413            Err(MapError::InvalidMinimumGap)
414        );
415    }
416}