reverse-geocoder-cn 0.1.0

离线为中国的区县进行逆地理编码;Offline reverse geocoding for Chinese province, city and county boundaries
Documentation
//! In-memory spatial index and reverse-geocoding API.

use std::{fs, path::Path};

use rstar::{AABB, RTree, RTreeObject};

use crate::{
    error::{CoordinateParseError, Error},
    store::{Area, read_data},
};

/// A resolved Chinese administrative address.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Address {
    pub province: AdministrativeArea,
    pub city: AdministrativeArea,
    pub county: AdministrativeArea,
}

/// A province, prefecture/city, or county/district. `code` is a six-digit code.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AdministrativeArea {
    pub name: String,
    pub code: String,
}

/// A local, read-only reverse geocoder.
pub struct ReverseGeocoder {
    provinces: Layer,
    cities: Layer,
    counties: Layer,
}

impl ReverseGeocoder {
    /// Loads the `cn_admin.bin` bundled with this crate. No separate data-file
    /// download or local build is needed for ordinary users.
    pub fn embedded() -> Result<Self, Error> {
        Self::from_bytes(include_bytes!("../cn_admin.bin"))
    }

    /// Opens a binary data file generated by `build-data`.
    pub fn open(path: impl AsRef<Path>) -> Result<Self, Error> {
        Self::from_bytes(&fs::read(path)?)
    }

    /// Loads a binary data file from memory, including one embedded with `include_bytes!`.
    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),
        })
    }

    /// Looks up decimal `(latitude, longitude)` coordinates.
    /// A coordinate outside the bundled China boundaries returns `None`.
    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])
    }

    /// Looks up degree-minute latitude and longitude, for example
    /// `reverse_geocode_degree_minutes("42°16.9552000'N", "126°36.5127000'E")`.
    ///
    /// A valid coordinate outside the bundled China boundaries returns `Ok(None)`.
    /// Invalid coordinate text returns [`CoordinateParseError`].
    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()
        );
    }
}