reverse-geocoder-cn 0.1.0

离线为中国的区县进行逆地理编码;Offline reverse geocoding for Chinese province, city and county boundaries
Documentation
//! Binary data storage and GeoJSON-to-binary conversion.

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

use serde::{Deserialize, Serialize};

use crate::{
    AdministrativeArea,
    error::{BuildError, Error},
};

// File signature + format version. It prevents arbitrary/corrupt files from
// being passed to bincode. `1` is the current on-disk format version.
const DATA_FILE_HEADER: &[u8; 8] = b"RCNGBIN1";

/// Builds a distributable binary data file from province, city and county GeoJSON files.
pub fn build_data(
    province_geojson: impl AsRef<Path>,
    city_geojson: impl AsRef<Path>,
    county_geojson: impl AsRef<Path>,
) -> Result<Vec<u8>, BuildError> {
    let data = DataFile {
        provinces: parse_geojson(province_geojson.as_ref())?,
        cities: parse_geojson(city_geojson.as_ref())?,
        counties: parse_geojson(county_geojson.as_ref())?,
    };
    let mut bytes = DATA_FILE_HEADER.to_vec();
    bytes.extend(bincode::serde::encode_to_vec(
        data,
        bincode::config::standard(),
    )?);
    Ok(bytes)
}

pub(crate) fn read_data(bytes: &[u8]) -> Result<DataFile, Error> {
    if bytes.len() < DATA_FILE_HEADER.len() || &bytes[..DATA_FILE_HEADER.len()] != DATA_FILE_HEADER
    {
        return Err(Error::InvalidData("not a reverse-geocoder-cn data file"));
    }
    let (data, used): (DataFile, usize) = bincode::serde::decode_from_slice(
        &bytes[DATA_FILE_HEADER.len()..],
        bincode::config::standard(),
    )
    .map_err(Error::Decode)?;
    if DATA_FILE_HEADER.len() + used != bytes.len() {
        return Err(Error::InvalidData("unexpected bytes after data file"));
    }
    Ok(data)
}

#[derive(Serialize, Deserialize)]
pub(crate) struct DataFile {
    pub(crate) provinces: Vec<Area>,
    pub(crate) cities: Vec<Area>,
    pub(crate) counties: Vec<Area>,
}

#[derive(Clone, Serialize, Deserialize)]
pub(crate) struct Area {
    pub(crate) name: String,
    pub(crate) code: String,
    /// MultiPolygon: polygons → rings → `[longitude, latitude]`.
    pub(crate) polygons: Vec<Vec<Vec<[f64; 2]>>>,
    pub(crate) bbox: [f64; 4],
}

impl Area {
    pub(crate) fn public(&self) -> AdministrativeArea {
        AdministrativeArea {
            name: self.name.clone(),
            code: self.code.clone(),
        }
    }
}

fn parse_geojson(path: &Path) -> Result<Vec<Area>, BuildError> {
    let document: GeoJson = serde_json::from_slice(&fs::read(path)?)?;
    if document.kind != "FeatureCollection" {
        return Err(BuildError::InvalidGeoJson(format!(
            "{} is not a FeatureCollection",
            path.display()
        )));
    }
    document
        .features
        .into_iter()
        // Tianditu's files include `境界线` MultiLineString overlays, which are not areas.
        .filter(|feature| matches!(feature.geometry.kind.as_str(), "Polygon" | "MultiPolygon"))
        .map(|feature| {
            let name = feature
                .properties
                .get("name")
                .and_then(JsonValue::as_str)
                .ok_or_else(|| {
                    BuildError::InvalidGeoJson("feature missing properties.name".into())
                })?
                .to_owned();
            let gb = feature
                .properties
                .get("gb")
                .and_then(JsonValue::as_str)
                .ok_or_else(|| {
                    BuildError::InvalidGeoJson(format!("{name} missing properties.gb"))
                })?;
            let polygons = match feature.geometry.kind.as_str() {
                "Polygon" => vec![decode_polygon(&feature.geometry.coordinates)?],
                "MultiPolygon" => feature
                    .geometry
                    .coordinates
                    .as_array()
                    .ok_or_else(|| {
                        BuildError::InvalidGeoJson("invalid MultiPolygon coordinates".into())
                    })?
                    .iter()
                    .map(decode_polygon)
                    .collect::<Result<Vec<_>, _>>()?,
                _ => unreachable!("non-polygon features were filtered above"),
            };
            let bbox = calculate_bbox(&polygons)
                .ok_or_else(|| BuildError::InvalidGeoJson(format!("{name} has no coordinates")))?;
            Ok(Area {
                name,
                code: gb.strip_prefix("156").unwrap_or(gb).to_owned(),
                polygons,
                bbox,
            })
        })
        .collect()
}

fn decode_polygon(value: &JsonValue) -> Result<Vec<Vec<[f64; 2]>>, BuildError> {
    value
        .as_array()
        .ok_or_else(|| BuildError::InvalidGeoJson("invalid polygon coordinates".into()))?
        .iter()
        .map(|ring| {
            ring.as_array()
                .ok_or_else(|| BuildError::InvalidGeoJson("invalid ring".into()))?
                .iter()
                .map(|point| {
                    let point = point
                        .as_array()
                        .ok_or_else(|| BuildError::InvalidGeoJson("invalid coordinate".into()))?;
                    if point.len() < 2 {
                        return Err(BuildError::InvalidGeoJson(
                            "coordinate needs two values".into(),
                        ));
                    }
                    Ok([
                        point[0].as_f64().ok_or_else(|| {
                            BuildError::InvalidGeoJson("longitude is not a number".into())
                        })?,
                        point[1].as_f64().ok_or_else(|| {
                            BuildError::InvalidGeoJson("latitude is not a number".into())
                        })?,
                    ])
                })
                .collect()
        })
        .collect()
}

fn calculate_bbox(polygons: &[Vec<Vec<[f64; 2]>>]) -> Option<[f64; 4]> {
    let mut bbox = [
        f64::INFINITY,
        f64::INFINITY,
        f64::NEG_INFINITY,
        f64::NEG_INFINITY,
    ];
    let mut found = false;
    for point in polygons.iter().flatten().flatten() {
        bbox[0] = bbox[0].min(point[0]);
        bbox[1] = bbox[1].min(point[1]);
        bbox[2] = bbox[2].max(point[0]);
        bbox[3] = bbox[3].max(point[1]);
        found = true;
    }
    found.then_some(bbox)
}

#[derive(Deserialize)]
struct GeoJson {
    #[serde(rename = "type")]
    kind: String,
    features: Vec<Feature>,
}
#[derive(Deserialize)]
struct Feature {
    properties: BTreeMap<String, JsonValue>,
    geometry: Geometry,
}
#[derive(Deserialize)]
struct Geometry {
    #[serde(rename = "type")]
    kind: String,
    coordinates: JsonValue,
}
type JsonValue = serde_json::Value;