#![forbid(unsafe_code)]
#![warn(missing_docs)]
use std::cmp::Reverse;
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
pub const GSI_VECTOR_TILE_URL: &str = "https://maps.gsi.go.jp/development/vt_expt.html";
pub const GSI_MAPS_VECTOR_URL: &str = "https://maps.gsi.go.jp/vector/";
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GeoPoint {
latitude: f64,
longitude: f64,
}
impl GeoPoint {
pub fn new(latitude: f64, longitude: f64) -> Result<Self, MapError> {
if !latitude.is_finite() || !(-90.0..=90.0).contains(&latitude) {
return Err(MapError::InvalidLatitude);
}
if !longitude.is_finite() || !(-180.0..=180.0).contains(&longitude) {
return Err(MapError::InvalidLongitude);
}
Ok(Self {
latitude,
longitude,
})
}
pub const fn latitude(self) -> f64 {
self.latitude
}
pub const fn longitude(self) -> f64 {
self.longitude
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Viewport {
south: f64,
west: f64,
north: f64,
east: f64,
}
impl Viewport {
pub fn new(south: f64, west: f64, north: f64, east: f64) -> Result<Self, MapError> {
GeoPoint::new(south, west)?;
GeoPoint::new(north, east)?;
if south >= north {
return Err(MapError::InvalidViewport);
}
Ok(Self {
south,
west,
north,
east,
})
}
pub fn contains(self, point: GeoPoint) -> bool {
let latitude_inside = (self.south..=self.north).contains(&point.latitude);
let longitude_inside = if self.west <= self.east {
(self.west..=self.east).contains(&point.longitude)
} else {
point.longitude >= self.west || point.longitude <= self.east
};
latitude_inside && longitude_inside
}
pub fn project(self, point: GeoPoint) -> Option<ScreenPoint> {
if !self.contains(point) {
return None;
}
let width = if self.west <= self.east {
self.east - self.west
} else {
(180.0 - self.west) + (self.east + 180.0)
};
let offset = if self.west <= self.east || point.longitude >= self.west {
point.longitude - self.west
} else {
(180.0 - self.west) + (point.longitude + 180.0)
};
let x = if width == 0.0 { 0.5 } else { offset / width };
let y = (self.north - point.latitude) / (self.north - self.south);
Some(ScreenPoint { x, y })
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScreenPoint {
x: f64,
y: f64,
}
impl ScreenPoint {
pub const fn x(self) -> f64 {
self.x
}
pub const fn y(self) -> f64 {
self.y
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LocalizedLabel {
values: BTreeMap<String, String>,
}
impl LocalizedLabel {
pub fn new() -> Self {
Self::default()
}
pub fn insert(
&mut self,
language: impl Into<String>,
value: impl Into<String>,
) -> Result<(), MapError> {
let language = language.into();
let value = value.into();
if language.trim().is_empty() || value.trim().is_empty() {
return Err(MapError::EmptyLabelValue);
}
self.values.insert(language, value);
Ok(())
}
pub fn get_with_fallback(&self, requested: &str, fallback: &str) -> Option<&str> {
self.values
.get(requested)
.or_else(|| self.values.get(fallback))
.map(String::as_str)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum LabelPriority {
Background,
Local,
Landmark,
Transit,
Emergency,
}
#[derive(Debug, Clone, PartialEq)]
pub struct MapFeature {
id: String,
point: GeoPoint,
label: LocalizedLabel,
priority: LabelPriority,
min_zoom: u8,
max_zoom: u8,
}
impl MapFeature {
pub fn new(
id: impl Into<String>,
point: GeoPoint,
label: LocalizedLabel,
priority: LabelPriority,
min_zoom: u8,
max_zoom: u8,
) -> Result<Self, MapError> {
let id = id.into();
if id.trim().is_empty() {
return Err(MapError::EmptyFeatureId);
}
if label.values.is_empty() {
return Err(MapError::MissingLabel);
}
if min_zoom > max_zoom {
return Err(MapError::InvalidZoomRange);
}
Ok(Self {
id,
point,
label,
priority,
min_zoom,
max_zoom,
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct PlacedLabel {
pub id: String,
pub text: String,
pub position: ScreenPoint,
pub priority: LabelPriority,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MapDisplay;
impl MapDisplay {
pub fn layout(
features: &[MapFeature],
viewport: Viewport,
zoom: u8,
requested_language: &str,
fallback_language: &str,
minimum_gap: f64,
) -> Result<Vec<PlacedLabel>, MapError> {
if !minimum_gap.is_finite() || minimum_gap < 0.0 {
return Err(MapError::InvalidMinimumGap);
}
let mut candidates: Vec<_> = features
.iter()
.filter(|feature| (feature.min_zoom..=feature.max_zoom).contains(&zoom))
.filter_map(|feature| {
let position = viewport.project(feature.point)?;
let text = feature
.label
.get_with_fallback(requested_language, fallback_language)?;
Some((feature, position, text))
})
.collect();
candidates.sort_by_key(|(feature, _, _)| (Reverse(feature.priority), feature.id.as_str()));
let mut placed: Vec<PlacedLabel> = Vec::new();
for (feature, position, text) in candidates {
let collides = placed.iter().any(|existing| {
let dx = existing.position.x - position.x;
let dy = existing.position.y - position.y;
dx.hypot(dy) < minimum_gap
});
if !collides {
placed.push(PlacedLabel {
id: feature.id.clone(),
text: text.to_owned(),
position,
priority: feature.priority,
});
}
}
Ok(placed)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MapError {
InvalidLatitude,
InvalidLongitude,
InvalidViewport,
EmptyLabelValue,
EmptyFeatureId,
MissingLabel,
InvalidZoomRange,
InvalidMinimumGap,
}
impl fmt::Display for MapError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let message = match self {
Self::InvalidLatitude => "latitude must be finite and within -90 to 90",
Self::InvalidLongitude => "longitude must be finite and within -180 to 180",
Self::InvalidViewport => "viewport must have a positive latitude span",
Self::EmptyLabelValue => "label language and value must not be blank",
Self::EmptyFeatureId => "feature id must not be blank",
Self::MissingLabel => "feature must have at least one label",
Self::InvalidZoomRange => "minimum zoom must not exceed maximum zoom",
Self::InvalidMinimumGap => "minimum gap must be finite and non-negative",
};
formatter.write_str(message)
}
}
impl Error for MapError {}
#[cfg(test)]
mod tests {
use super::*;
fn label(text: &str) -> LocalizedLabel {
let mut label = LocalizedLabel::new();
label.insert("ja", text).unwrap();
label
}
fn feature(id: &str, longitude: f64, priority: LabelPriority) -> MapFeature {
MapFeature::new(
id,
GeoPoint::new(0.0, longitude).unwrap(),
label(id),
priority,
0,
20,
)
.unwrap()
}
#[test]
fn invalid_coordinates_are_rejected() {
assert_eq!(GeoPoint::new(91.0, 0.0), Err(MapError::InvalidLatitude));
assert_eq!(
GeoPoint::new(0.0, f64::NAN),
Err(MapError::InvalidLongitude)
);
}
#[test]
fn antimeridian_viewport_projects_both_sides() {
let viewport = Viewport::new(-10.0, 170.0, 10.0, -170.0).unwrap();
let west_side = viewport
.project(GeoPoint::new(0.0, 175.0).unwrap())
.unwrap();
let east_side = viewport
.project(GeoPoint::new(0.0, -175.0).unwrap())
.unwrap();
assert!((west_side.x() - 0.25).abs() < 1e-12);
assert!((east_side.x() - 0.75).abs() < 1e-12);
}
#[test]
fn higher_priority_label_wins_collision() {
let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
let features = [
feature("local", 0.0, LabelPriority::Local),
feature("emergency", 0.01, LabelPriority::Emergency),
];
let placed = MapDisplay::layout(&features, viewport, 10, "ja", "ja", 0.1).unwrap();
assert_eq!(placed.len(), 1);
assert_eq!(placed[0].id, "emergency");
}
#[test]
fn zoom_and_language_filter_are_applied() {
let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
let mut localized = label("駅");
localized.insert("en", "Station").unwrap();
let feature = MapFeature::new(
"station",
GeoPoint::new(0.0, 0.0).unwrap(),
localized,
LabelPriority::Transit,
8,
12,
)
.unwrap();
assert!(
MapDisplay::layout(std::slice::from_ref(&feature), viewport, 7, "en", "ja", 0.0)
.unwrap()
.is_empty()
);
let placed = MapDisplay::layout(&[feature], viewport, 10, "en", "ja", 0.0).unwrap();
assert_eq!(placed[0].text, "Station");
}
#[test]
fn invalid_layout_gap_is_rejected() {
let viewport = Viewport::new(-1.0, -1.0, 1.0, 1.0).unwrap();
assert_eq!(
MapDisplay::layout(&[], viewport, 1, "ja", "ja", -0.1),
Err(MapError::InvalidMinimumGap)
);
}
}