use std::collections::HashMap;
use geo::Centroid;
use serde_json::{Map, Value, json};
use crate::importance::{POI_RANK, default_importance};
use crate::record::{AddressFields, GeocodingLayer, GeocodingRecord, RecordInit};
use geolith::admin::AdminHierarchyIndex;
use geolith::source::input::{DataSource, InputFeature};
use geolith::source::reader::SOURCE_ID_PROP;
use geolith::tile::feature::PropValue;
fn prop_str<'a>(feature: &'a InputFeature, key: &str) -> Option<&'a str> {
match feature.properties.get(key) {
Some(PropValue::Str(s)) if !s.is_empty() => Some(s),
_ => None,
}
}
fn prop_f64(feature: &InputFeature, key: &str) -> Option<f64> {
match feature.properties.get(key) {
Some(PropValue::F64(v)) => Some(*v),
Some(PropValue::I64(v)) => Some(*v as f64),
_ => None,
}
}
fn centroid_lon_lat(feature: &InputFeature) -> Option<(f64, f64)> {
let (lon, lat) = match feature.geometry.as_ref() {
geo::Geometry::Point(p) => (p.x(), p.y()),
other => other.centroid().map(|c| (c.x(), c.y()))?,
};
if crate::record::valid_point(lon, lat) {
Some((lon, lat))
} else {
crate::record::count_bad_point();
None
}
}
fn priority_categories(feature: &InputFeature) -> Vec<String> {
let mut out: Vec<String> = Vec::with_capacity(4);
let mut push_unique = |value: &str| {
let v = value.trim();
if !v.is_empty() && !out.iter().any(|existing| existing == v) {
out.push(v.to_string());
}
};
if let Some(basic) = prop_str(feature, "basic_category") {
push_unique(basic);
}
for key in [
"taxonomy.primary",
"categories.primary",
"categories.main",
"category",
] {
if let Some(v) = prop_str(feature, key) {
push_unique(v);
}
}
out
}
fn multilingual_names(feature: &InputFeature) -> HashMap<String, String> {
let mut names = HashMap::new();
for (key, value) in &feature.properties {
if let Some(lang) = key.strip_prefix("names.common.")
&& let PropValue::Str(v) = value
&& !v.is_empty()
{
names.insert(lang.to_string(), v.clone());
}
}
names
}
fn overture_addendum(feature: &InputFeature, theme: &str, otype: &str) -> Value {
let mut addendum = Map::new();
addendum.insert("theme".to_string(), json!(theme));
addendum.insert("type".to_string(), json!(otype));
if let Some(conf) = prop_f64(feature, "confidence") {
addendum.insert("confidence".to_string(), json!(conf));
}
if let Some(basic) = prop_str(feature, "basic_category") {
addendum.insert("basic_category".to_string(), json!(basic));
}
for (key, target) in [
("websites", "websites"),
("phones", "phones"),
("emails", "emails"),
("socials", "socials"),
("operating_status", "operating_status"),
] {
if let Some(v) = prop_str(feature, key) {
addendum.insert(target.to_string(), json!(v));
}
}
if let Some(PropValue::I64(version)) = feature.properties.get("version") {
addendum.insert("version".to_string(), json!(version));
}
Value::Object(addendum)
}
#[must_use]
pub fn overture_place_record(
feature: &InputFeature,
admin_index: &AdminHierarchyIndex,
) -> Option<GeocodingRecord> {
let DataSource::Overture { theme, otype } = &feature.source else {
return None;
};
let name = prop_str(feature, "names.primary")?.to_string();
let (lon, lat) = centroid_lon_lat(feature)?;
let admin = admin_index.resolve(lon, lat);
let mut record = GeocodingRecord::new(RecordInit {
id: feature.id,
source: feature.source.clone(),
layer: GeocodingLayer::Venue,
name,
lon,
lat,
admin,
address: None,
names: multilingual_names(feature),
importance: default_importance(POI_RANK),
})
.with_categories(priority_categories(feature))
.with_addendum("overture", overture_addendum(feature, theme, otype));
if let Some(source_id) = prop_str(feature, SOURCE_ID_PROP) {
record = record.with_source_id(source_id);
}
Some(record)
}
#[must_use]
pub fn overture_address_record(
feature: &InputFeature,
admin_index: &AdminHierarchyIndex,
) -> Option<GeocodingRecord> {
let DataSource::Overture { theme, otype } = &feature.source else {
return None;
};
let street = prop_str(feature, "street").map(str::to_string);
let number = prop_str(feature, "number").map(str::to_string);
if street.is_none() && number.is_none() {
return None;
}
let name = match (&number, &street) {
(Some(n), Some(s)) => format!("{n} {s}"),
(Some(n), None) => n.clone(),
(None, Some(s)) => s.clone(),
(None, None) => return None,
};
let (lon, lat) = centroid_lon_lat(feature)?;
let mut admin = admin_index.resolve(lon, lat);
if admin.country_code.is_none()
&& let Some(cc) = prop_str(feature, "country")
{
admin.country_code = Some(cc.to_uppercase());
}
if admin.locality.is_none()
&& let Some(city) = prop_str(feature, "postal_city")
{
admin.locality = Some(city.to_string());
}
let address = AddressFields {
number,
street,
unit: prop_str(feature, "unit").map(str::to_string),
postcode: prop_str(feature, "postcode").map(str::to_string),
city: prop_str(feature, "postal_city").map(str::to_string),
};
let mut addendum = Map::new();
addendum.insert("theme".to_string(), json!(theme));
addendum.insert("type".to_string(), json!(otype));
if let Some(city) = prop_str(feature, "postal_city") {
addendum.insert("postal_city".to_string(), json!(city));
}
if let Some(cc) = prop_str(feature, "country") {
addendum.insert("country".to_string(), json!(cc));
}
if let Some(unit) = &address.unit {
addendum.insert("unit".to_string(), json!(unit));
}
let mut record = GeocodingRecord::new(RecordInit {
id: feature.id,
source: feature.source.clone(),
layer: GeocodingLayer::Address,
name,
lon,
lat,
admin,
address: Some(address),
names: HashMap::new(),
importance: default_importance(POI_RANK),
})
.with_addendum("overture", Value::Object(addendum));
if let Some(source_id) = prop_str(feature, SOURCE_ID_PROP) {
record = record.with_source_id(source_id);
}
Some(record)
}
#[cfg(test)]
mod tests {
use super::*;
use geolith::admin::AdminHierarchyBuilder;
use std::sync::Arc;
fn overture_feature(
theme: &str,
otype: &str,
props: &[(&str, PropValue)],
lon: f64,
lat: f64,
) -> InputFeature {
InputFeature {
id: 7,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(lon, lat))),
properties: props
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect(),
bbox: None,
source: DataSource::Overture {
theme: theme.to_string(),
otype: otype.to_string(),
},
}
}
fn empty_index() -> AdminHierarchyIndex {
AdminHierarchyBuilder::new().build().unwrap()
}
#[test]
fn place_record_requires_primary_name() {
let feature = overture_feature(
"places",
"place",
&[("confidence", PropValue::F64(0.9))],
77.0,
28.0,
);
assert!(overture_place_record(&feature, &empty_index()).is_none());
}
#[test]
fn place_record_builds_venue_with_categories_and_addendum() {
let feature = overture_feature(
"places",
"place",
&[
(
"names.primary",
PropValue::Str("Blue Bottle Coffee".to_string()),
),
("basic_category", PropValue::Str("cafe".to_string())),
(
"categories.primary",
PropValue::Str("coffee_shop".to_string()),
),
("confidence", PropValue::F64(0.97)),
(
SOURCE_ID_PROP,
PropValue::Str("08F2A100D388CFFF".to_string()),
),
],
-122.42,
37.77,
);
let record = overture_place_record(&feature, &empty_index()).expect("record");
assert_eq!(record.layer, GeocodingLayer::Venue);
assert_eq!(record.name, "Blue Bottle Coffee");
assert_eq!(record.categories, vec!["cafe", "coffee_shop"]);
assert_eq!(record.source_id.as_deref(), Some("08F2A100D388CFFF"));
assert!((record.importance - 0.000_01).abs() < 1e-6);
let addendum = record.addendum.get("overture").expect("overture ns");
assert_eq!(addendum["theme"], "places");
assert_eq!(addendum["confidence"], 0.97);
assert_eq!(addendum["basic_category"], "cafe");
}
#[test]
fn place_record_dedupes_categories() {
let feature = overture_feature(
"places",
"place",
&[
("names.primary", PropValue::Str("X".to_string())),
("basic_category", PropValue::Str("cafe".to_string())),
("categories.primary", PropValue::Str("cafe".to_string())),
],
0.0,
0.0,
);
let record = overture_place_record(&feature, &empty_index()).expect("record");
assert_eq!(record.categories, vec!["cafe"]);
}
#[test]
fn place_record_collects_multilingual_names() {
let feature = overture_feature(
"places",
"place",
&[
("names.primary", PropValue::Str("Beijing".to_string())),
("names.common.zh", PropValue::Str("北京".to_string())),
],
116.0,
40.0,
);
let record = overture_place_record(&feature, &empty_index()).expect("record");
assert_eq!(record.names.get("zh").map(String::as_str), Some("北京"));
}
#[test]
fn address_record_requires_street_or_number() {
let feature = overture_feature("addresses", "address", &[], 0.0, 0.0);
assert!(overture_address_record(&feature, &empty_index()).is_none());
}
#[test]
fn address_record_builds_full_address() {
let feature = overture_feature(
"addresses",
"address",
&[
("number", PropValue::Str("123".to_string())),
("street", PropValue::Str("Main Street".to_string())),
("unit", PropValue::Str("5A".to_string())),
("postcode", PropValue::Str("10001".to_string())),
("country", PropValue::Str("us".to_string())),
("postal_city", PropValue::Str("New York".to_string())),
("__source_id", PropValue::Str("abc123".to_string())),
],
-73.98,
40.74,
);
let record = overture_address_record(&feature, &empty_index()).expect("record");
assert_eq!(record.layer, GeocodingLayer::Address);
assert_eq!(record.name, "123 Main Street");
let addr = record.address.as_ref().expect("address");
assert_eq!(addr.number.as_deref(), Some("123"));
assert_eq!(addr.street.as_deref(), Some("Main Street"));
assert_eq!(addr.unit.as_deref(), Some("5A"));
assert_eq!(addr.postcode.as_deref(), Some("10001"));
assert_eq!(record.country_code.as_deref(), Some("US"));
assert_eq!(record.admin.locality.as_deref(), Some("New York"));
assert_eq!(record.source_id.as_deref(), Some("abc123"));
let addendum = record.addendum.get("overture").expect("ns");
assert_eq!(addendum["postal_city"], "New York");
}
#[test]
fn place_record_polygon_centroid_and_contact_addendum() {
let square = geo::Polygon::new(
geo::LineString::from(vec![
(0.0, 0.0),
(2.0, 0.0),
(2.0, 2.0),
(0.0, 2.0),
(0.0, 0.0),
]),
vec![],
);
let mut feature = overture_feature(
"places",
"place",
&[
("names.primary", PropValue::Str("Plaza".to_string())),
(
"websites",
PropValue::Str("https://example.com".to_string()),
),
("phones", PropValue::Str("+1-555-0100".to_string())),
("emails", PropValue::Str("hi@example.com".to_string())),
("socials", PropValue::Str("@plaza".to_string())),
("operating_status", PropValue::Str("open".to_string())),
("version", PropValue::I64(3)),
("confidence", PropValue::I64(1)),
],
0.0,
0.0,
);
feature.geometry = Arc::new(geo::Geometry::Polygon(square));
let record = overture_place_record(&feature, &empty_index()).expect("record");
assert!((record.lon - 1.0).abs() < 1e-9, "polygon centroid lon");
assert!((record.lat - 1.0).abs() < 1e-9, "polygon centroid lat");
let addendum = record.addendum.get("overture").expect("ns");
assert_eq!(addendum["confidence"], 1.0, "I64 confidence");
assert_eq!(addendum["websites"], "https://example.com");
assert_eq!(addendum["phones"], "+1-555-0100");
assert_eq!(addendum["emails"], "hi@example.com");
assert_eq!(addendum["socials"], "@plaza");
assert_eq!(addendum["operating_status"], "open");
assert_eq!(addendum["version"], 3);
}
#[test]
fn address_record_street_only() {
let feature = overture_feature(
"addresses",
"address",
&[("street", PropValue::Str("Broadway".to_string()))],
1.0,
2.0,
);
let record = overture_address_record(&feature, &empty_index()).expect("record");
assert_eq!(record.name, "Broadway");
let addr = record.address.as_ref().expect("address");
assert!(addr.number.is_none());
assert_eq!(addr.street.as_deref(), Some("Broadway"));
}
#[test]
fn address_record_number_only() {
let feature = overture_feature(
"addresses",
"address",
&[("number", PropValue::Str("42".to_string()))],
1.0,
2.0,
);
let record = overture_address_record(&feature, &empty_index()).expect("record");
assert_eq!(record.name, "42");
}
#[test]
fn non_overture_source_returns_none() {
let feature = InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
properties: HashMap::new(),
bbox: None,
source: DataSource::LandPolygons,
};
assert!(overture_place_record(&feature, &empty_index()).is_none());
assert!(overture_address_record(&feature, &empty_index()).is_none());
}
#[test]
fn a_point_that_is_not_a_place_on_earth_is_refused_and_counted() {
let index = empty_index();
let name = [("names.primary", PropValue::Str("Nowhere".into()))];
let before = crate::record::bad_points();
for (lon, lat) in [
(f64::NAN, 10.0),
(10.0, f64::INFINITY),
(181.0, 0.0),
(0.0, -90.5),
] {
let feature = overture_feature("places", "place", &name, lon, lat);
assert!(
overture_place_record(&feature, &index).is_none(),
"({lon}, {lat}) is not on Earth"
);
}
assert!(crate::record::bad_points() >= before + 4);
let corner = overture_feature("places", "place", &name, 180.0, -90.0);
assert!(
overture_place_record(&corner, &index).is_some(),
"the corners are valid"
);
}
}