use std::{fs, path::Path};
use rstar::{AABB, RTree, RTreeObject};
use crate::{
error::{CoordinateParseError, Error},
store::{Area, read_data},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Address {
pub province: AdministrativeArea,
pub city: AdministrativeArea,
pub county: AdministrativeArea,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdministrativeArea {
pub name: String,
pub code: String,
}
pub struct ReverseGeocoder {
provinces: Layer,
cities: Layer,
counties: Layer,
}
impl ReverseGeocoder {
pub fn embedded() -> Result<Self, Error> {
Self::from_bytes(include_bytes!("../cn_admin.bin"))
}
pub fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
Self::from_bytes(&fs::read(path)?)
}
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
let data = read_data(bytes)?;
Ok(Self {
provinces: Layer::new(data.provinces),
cities: Layer::new(data.cities),
counties: Layer::new(data.counties),
})
}
pub fn reverse_geocode(&self, latitude: f64, longitude: f64) -> Option<Address> {
if !(-90.0..=90.0).contains(&latitude) || !(-180.0..=180.0).contains(&longitude) {
return None;
}
self.lookup([longitude, latitude])
}
pub fn reverse_geocode_degree_minutes(
&self,
latitude: &str,
longitude: &str,
) -> Result<Option<Address>, CoordinateParseError> {
let latitude = parse_coordinate(latitude, true)?;
let longitude = parse_coordinate(longitude, false)?;
let point = [longitude, latitude];
Ok(self.lookup(point))
}
fn lookup(&self, point: [f64; 2]) -> Option<Address> {
Some(Address {
province: self.provinces.find(point)?.public(),
city: self.cities.find(point)?.public(),
county: self.counties.find(point)?.public(),
})
}
}
fn parse_coordinate(token: &str, latitude: bool) -> Result<f64, CoordinateParseError> {
let hemisphere = token
.chars()
.last()
.ok_or(CoordinateParseError("empty coordinate"))?
.to_ascii_uppercase();
let valid_direction = if latitude {
matches!(hemisphere, 'N' | 'S')
} else {
matches!(hemisphere, 'E' | 'W')
};
if !valid_direction {
return Err(CoordinateParseError(if latitude {
"latitude must end in N or S"
} else {
"longitude must end in E or W"
}));
}
let value = token[..token.len() - hemisphere.len_utf8()].trim_end_matches(['\'', '′', '’']);
let (degrees, minutes) = value.split_once('°').ok_or(CoordinateParseError(
"coordinate is missing the degree symbol",
))?;
let degrees = degrees
.parse::<u16>()
.map_err(|_| CoordinateParseError("invalid degrees"))?;
let minutes = minutes
.parse::<f64>()
.map_err(|_| CoordinateParseError("invalid minutes"))?;
let maximum = if latitude { 90 } else { 180 };
if !(0.0..60.0).contains(&minutes) || degrees > maximum || (degrees == maximum && minutes > 0.0)
{
return Err(CoordinateParseError("coordinate is out of range"));
}
let decimal = f64::from(degrees) + minutes / 60.0;
Ok(if matches!(hemisphere, 'S' | 'W') {
-decimal
} else {
decimal
})
}
struct IndexedArea {
index: usize,
bbox: AABB<[f64; 2]>,
}
impl RTreeObject for IndexedArea {
type Envelope = AABB<[f64; 2]>;
fn envelope(&self) -> Self::Envelope {
self.bbox
}
}
struct Layer {
areas: Vec<Area>,
index: RTree<IndexedArea>,
}
impl Layer {
fn new(areas: Vec<Area>) -> Self {
let index = RTree::bulk_load(
areas
.iter()
.enumerate()
.map(|(index, area)| IndexedArea {
index,
bbox: AABB::from_corners(
[area.bbox[0], area.bbox[1]],
[area.bbox[2], area.bbox[3]],
),
})
.collect(),
);
Self { areas, index }
}
fn find(&self, point: [f64; 2]) -> Option<&Area> {
self.index
.locate_in_envelope_intersecting(AABB::from_point(point))
.find_map(|item| {
self.areas
.get(item.index)
.filter(|area| contains(area, point))
})
}
}
fn contains(area: &Area, point: [f64; 2]) -> bool {
area.polygons.iter().any(|polygon| {
polygon
.first()
.is_some_and(|outer| point_in_ring(point, outer))
&& polygon
.iter()
.skip(1)
.all(|hole| !point_in_ring(point, hole))
})
}
fn point_in_ring(point: [f64; 2], ring: &[[f64; 2]]) -> bool {
if ring.len() < 3 {
return false;
}
let mut inside = false;
for index in 0..ring.len() {
let (a, b) = (ring[index], ring[(index + 1) % ring.len()]);
if on_segment(point, a, b) {
return true;
}
if (a[1] > point[1]) != (b[1] > point[1])
&& point[0] < (b[0] - a[0]) * (point[1] - a[1]) / (b[1] - a[1]) + a[0]
{
inside = !inside;
}
}
inside
}
fn on_segment(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> bool {
const EPSILON: f64 = 1e-10;
let cross = (p[1] - a[1]) * (b[0] - a[0]) - (p[0] - a[0]) * (b[1] - a[1]);
cross.abs() <= EPSILON
&& p[0] >= a[0].min(b[0]) - EPSILON
&& p[0] <= a[0].max(b[0]) + EPSILON
&& p[1] >= a[1].min(b[1]) - EPSILON
&& p[1] <= a[1].max(b[1]) + EPSILON
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn embedded_data_resolves_tiananmen() {
let result = ReverseGeocoder::embedded()
.unwrap()
.reverse_geocode(39.9087, 116.3975)
.unwrap();
assert_eq!(result.county.code, "110101");
}
#[test]
fn degree_minute_coordinates_resolve_and_outside_china_returns_none() {
let geocoder = ReverseGeocoder::embedded().unwrap();
let jilin = geocoder
.reverse_geocode_degree_minutes("42°16.9552000'N", "126°36.5127000'E")
.unwrap()
.unwrap();
let south_china = geocoder
.reverse_geocode_degree_minutes("22°09.8935000'N", "113°33.4033000'E")
.unwrap()
.unwrap();
assert_eq!(jilin.province.name, "吉林省");
assert_eq!(jilin.city.code, "220600");
assert_eq!(jilin.county.code, "220622");
assert_eq!(south_china.province.code, "820000");
assert_eq!(south_china.county.name, "澳门特别行政区");
assert_eq!(geocoder.reverse_geocode(40.7128, -74.0060), None);
assert_eq!(
geocoder.reverse_geocode_degree_minutes("40°42.768'N", "74°00.36'W"),
Ok(None)
);
}
#[test]
fn invalid_degree_minute_coordinates_return_an_error() {
let geocoder = ReverseGeocoder::embedded().unwrap();
assert!(
geocoder
.reverse_geocode_degree_minutes("42°61'N", "126°36'E")
.is_err()
);
}
}