use std::collections::HashMap;
use std::sync::OnceLock;
use geolith::names::push_names;
use crate::layers::{Layer, mark_foreign};
use crate::source::input::{DataSource, InputFeature};
use crate::tile::feature::PropValue;
use super::buildings::ProcessedFeature;
const WIKIDATA_CSV: &str = include_str!("places-wikidata.csv");
#[derive(Debug, Clone, Copy)]
struct WikidataZoom {
min_zoom: u8,
max_zoom: Option<u8>,
rank_max: Option<u8>,
}
fn parse_wikidata_row(row: &str) -> Option<(&str, WikidataZoom)> {
let mut columns = row.split(',');
let id = columns.next()?;
let mut number = || columns.next()?.trim().parse::<i16>().ok();
let (min_zoom, max_zoom, rank_max) = (number()?, number()?, number()?);
Some((
id,
WikidataZoom {
min_zoom: u8::try_from(min_zoom).ok()?,
max_zoom: u8::try_from(max_zoom).ok(),
rank_max: u8::try_from(rank_max).ok(),
},
))
}
fn wikidata_zoom(id: &str) -> Option<WikidataZoom> {
static TABLE: OnceLock<HashMap<&'static str, WikidataZoom>> = OnceLock::new();
TABLE
.get_or_init(|| {
WIKIDATA_CSV
.lines()
.skip(1)
.filter_map(parse_wikidata_row)
.collect()
})
.get(id)
.copied()
}
struct Zooms {
min_zoom: u8,
max_zoom: u8,
population_rank: Option<u8>,
}
fn apply_wikidata(kind: &str, wikidata: Option<&str>, zooms: Zooms) -> Zooms {
let Some(row) = wikidata.and_then(wikidata_zoom) else {
return zooms;
};
match kind {
"country" | "region" => Zooms {
min_zoom: row.min_zoom,
max_zoom: row.max_zoom.unwrap_or(zooms.max_zoom),
..zooms
},
"locality" => Zooms {
min_zoom: row.min_zoom,
population_rank: row.rank_max.or(zooms.population_rank),
..zooms
},
_ => zooms,
}
}
const POP_BREAKS: &[u64] = &[
1_000_000_000,
100_000_000,
50_000_000,
20_000_000,
10_000_000,
5_000_000,
1_000_000,
500_000,
200_000,
100_000,
50_000,
20_000,
10_000,
5_000,
2_000,
1_000,
200,
0,
];
const REGION_COUNTRIES: &[&str] = &["US", "CA", "BR", "IN", "CN", "AU"];
fn population_rank(population: u64) -> u8 {
for (i, &threshold) in POP_BREAKS.iter().enumerate() {
if population >= threshold {
return (POP_BREAKS.len() - i) as u8;
}
}
0
}
pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
match &feature.source {
DataSource::Overture { .. } => process_overture(feature),
DataSource::Osm { .. } => process_osm(feature),
_ => None,
}
}
fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
let subtype = feature.get_str("subtype")?;
let class = feature.get_str("class");
let population = feature.get_i64("population");
let has_population = population.is_some_and(|p| p > 0);
let (kind, min_zoom) = match subtype {
"country" | "dependency" => ("country", 5u8),
"region" => ("region", 8),
"county" => ("county", 7),
"locality" => match class {
Some("city") => ("locality", if has_population { 7 } else { 8 }),
Some("town") => ("locality", if has_population { 7 } else { 9 }),
Some("village") => ("locality", 12),
Some("hamlet") => ("locality", 13),
_ => ("locality", 10),
},
"macrohood" => ("macrohood", 11),
"neighbourhood" | "neighborhood" => ("neighbourhood", 12),
"microhood" => ("neighbourhood", 13),
_ => return None,
};
let zooms = apply_wikidata(
kind,
feature.get_str("wikidata"),
Zooms {
min_zoom,
max_zoom: 15,
population_rank: population.map(|p| population_rank(p.max(0) as u64)),
},
);
let mut properties = Vec::with_capacity(7);
properties.push(("kind".into(), PropValue::Str(kind.into())));
if let Some(class) = class {
properties.push(("kind_detail".into(), PropValue::Str(class.to_string())));
}
if let Some(pop) = population {
properties.push(("population".into(), PropValue::I64(pop)));
}
if let Some(rank) = zooms.population_rank {
properties.push(("population_rank".into(), PropValue::I64(i64::from(rank))));
}
push_names(feature, &mut properties);
properties.push(("class".into(), PropValue::Str(kind.into())));
if let Some(wikidata) = feature.get_str("wikidata") {
properties.push(("wikidata".into(), PropValue::Str(wikidata.to_string())));
}
properties.push((
"min_zoom".into(),
PropValue::I64(i64::from(zooms.min_zoom) + 1),
));
if geolith::admin::soi_area::is_foreign_admin_area(
subtype,
feature.get_str("country"),
feature.get_str("region"),
) {
mark_foreign(&mut properties);
}
Some(ProcessedFeature {
id: feature.id,
geometry: feature.geometry.clone(),
layer: Layer::Places,
min_zoom: zooms.min_zoom,
max_zoom: zooms.max_zoom,
sort_rank: 300,
properties,
})
}
struct PlaceClass {
kind: &'static str,
min_zoom: u8,
max_zoom: u8,
kind_rank: u8,
default_pop: Option<u64>,
}
fn classify_place(place: &str, country_code: Option<&str>) -> Option<PlaceClass> {
match place {
"country" => Some(PlaceClass {
kind: "country",
min_zoom: 5,
max_zoom: 8,
kind_rank: 0,
default_pop: None,
}),
"state" | "province" => {
let is_major = country_code
.is_some_and(|cc| REGION_COUNTRIES.iter().any(|r| cc.eq_ignore_ascii_case(r)));
if is_major {
Some(PlaceClass {
kind: "region",
min_zoom: 8,
max_zoom: 11,
kind_rank: 1,
default_pop: None,
})
} else {
None
}
}
"city" => Some(PlaceClass {
kind: "locality",
min_zoom: 7,
max_zoom: 15,
kind_rank: 2,
default_pop: Some(5000),
}),
"town" => Some(PlaceClass {
kind: "locality",
min_zoom: 7,
max_zoom: 15,
kind_rank: 2,
default_pop: Some(10_000),
}),
"village" => Some(PlaceClass {
kind: "locality",
min_zoom: 10,
max_zoom: 15,
kind_rank: 3,
default_pop: Some(2000),
}),
"locality" => Some(PlaceClass {
kind: "locality",
min_zoom: 11,
max_zoom: 15,
kind_rank: 4,
default_pop: Some(1000),
}),
"hamlet" => Some(PlaceClass {
kind: "locality",
min_zoom: 11,
max_zoom: 15,
kind_rank: 5,
default_pop: Some(200),
}),
"isolated_dwelling" => Some(PlaceClass {
kind: "locality",
min_zoom: 13,
max_zoom: 15,
kind_rank: 6,
default_pop: Some(100),
}),
"farm" => Some(PlaceClass {
kind: "locality",
min_zoom: 13,
max_zoom: 15,
kind_rank: 7,
default_pop: Some(50),
}),
"allotments" => Some(PlaceClass {
kind: "locality",
min_zoom: 13,
max_zoom: 15,
kind_rank: 8,
default_pop: Some(1000),
}),
"suburb" => Some(PlaceClass {
kind: "neighbourhood",
min_zoom: 11,
max_zoom: 15,
kind_rank: 9,
default_pop: None,
}),
"quarter" => Some(PlaceClass {
kind: "macrohood",
min_zoom: 10,
max_zoom: 15,
kind_rank: 10,
default_pop: None,
}),
"neighbourhood" | "neighborhood" => Some(PlaceClass {
kind: "neighbourhood",
min_zoom: 12,
max_zoom: 15,
kind_rank: 11,
default_pop: None,
}),
_ => None,
}
}
fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
let place = feature.get_str("place")?;
if !feature.is_point() {
return None;
}
let country_code = feature
.get_str("addr:country")
.or(feature.get_str("is_in:country_code"))
.or(feature.get_str("ISO3166-1:alpha2"));
let class = classify_place(place, country_code)?;
let population = feature
.get_str("population")
.and_then(|s| s.replace(',', "").parse::<u64>().ok())
.or(feature.get_i64("population").map(|v| v.max(0) as u64))
.or(class.default_pop);
let has_explicit_pop = feature.has_key("population");
let adjusted_min_zoom = if !has_explicit_pop && class.default_pop.is_some() {
match place {
"city" => 8u8,
"town" => 9,
"village" => 11,
"locality" => 12,
"hamlet" => 12,
"isolated_dwelling" | "farm" | "allotments" => 14,
_ => class.min_zoom,
}
} else {
class.min_zoom
};
let zooms = apply_wikidata(
class.kind,
feature.get_str("wikidata"),
Zooms {
min_zoom: adjusted_min_zoom,
max_zoom: class.max_zoom,
population_rank: population.map(population_rank),
},
);
let sort_rank = 300 + i32::from(class.kind_rank);
let mut properties = Vec::with_capacity(8);
properties.push(("kind".into(), PropValue::Str(class.kind.into())));
properties.push(("kind_detail".into(), PropValue::Str(place.to_string())));
if let Some(pop) = population {
properties.push(("population".into(), PropValue::I64(pop as i64)));
}
if let Some(rank) = zooms.population_rank {
properties.push(("population_rank".into(), PropValue::I64(i64::from(rank))));
}
if let Some(capital) = feature.get_str("capital") {
properties.push(("capital".into(), PropValue::Str(capital.to_string())));
}
if let Some(wikidata) = feature.get_str("wikidata") {
properties.push(("wikidata".into(), PropValue::Str(wikidata.to_string())));
}
push_names(feature, &mut properties);
properties.push((
"min_zoom".into(),
PropValue::I64(i64::from(zooms.min_zoom) + 1),
));
Some(ProcessedFeature {
id: feature.id,
geometry: feature.geometry.clone(),
layer: Layer::Places,
min_zoom: zooms.min_zoom,
max_zoom: zooms.max_zoom,
sort_rank,
properties,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::source::input::{DataSource, OsmElementType};
use std::collections::HashMap;
use std::sync::Arc;
fn make_overture(props: &[(&str, PropValue)]) -> InputFeature {
let mut properties = HashMap::new();
for (k, v) in props {
properties.insert(k.to_string(), v.clone());
}
InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(2.35, 48.86))),
properties,
bbox: None,
source: DataSource::Overture {
theme: String::new(),
otype: String::new(),
},
}
}
fn make_osm(tags: &[(&str, &str)]) -> InputFeature {
let mut properties = HashMap::new();
for (k, v) in tags {
properties.insert(k.to_string(), PropValue::Str(v.to_string()));
}
InputFeature {
id: 42,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(2.35, 48.86))),
properties,
bbox: None,
source: DataSource::Osm {
element_type: OsmElementType::Node,
relations: vec![],
},
}
}
#[test]
fn overture_country_has_correct_kind_and_zoom() {
let feat = make_overture(&[("subtype", PropValue::Str("country".into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.layer, Layer::Places);
assert_eq!(result.min_zoom, 5);
assert_eq!(result.sort_rank, 300);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
);
}
#[test]
fn overture_locality_without_class_starts_at_zoom_10() {
let feat = make_overture(&[("subtype", PropValue::Str("locality".into()))]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 10);
assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(11)));
}
#[test]
fn overture_population_rank_calculated() {
let feat = make_overture(&[
("subtype", PropValue::Str("locality".into())),
("population", PropValue::I64(5_000_000)),
]);
let result = process(&feat).unwrap();
let rank = result
.properties
.iter()
.find(|(k, _)| k == "population_rank")
.map(|(_, v)| v.clone());
assert_eq!(rank, Some(PropValue::I64(13)));
}
fn prop<'a>(r: &'a ProcessedFeature, key: &str) -> Option<&'a PropValue> {
r.properties.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
#[test]
fn overture_locality_zoom_follows_class() {
let cases = [
(Some("city"), 8u8),
(Some("town"), 9),
(None, 10),
(Some("village"), 12),
(Some("hamlet"), 13),
];
for (class, zoom) in cases {
let mut props = vec![("subtype", PropValue::Str("locality".into()))];
if let Some(c) = class {
props.push(("class", PropValue::Str(c.into())));
}
let r = process(&make_overture(&props)).unwrap();
assert_eq!(
prop(&r, "kind"),
Some(&PropValue::Str("locality".into())),
"{class:?}"
);
assert_eq!(r.min_zoom, zoom, "{class:?}");
assert_eq!(
prop(&r, "kind_detail"),
class.map(|c| PropValue::Str(c.into())).as_ref(),
"{class:?}"
);
}
}
#[test]
fn overture_city_and_town_with_population_start_at_zoom_7() {
for class in ["city", "town"] {
let r = process(&make_overture(&[
("subtype", PropValue::Str("locality".into())),
("class", PropValue::Str(class.into())),
("population", PropValue::I64(250_000)),
]))
.unwrap();
assert_eq!(r.min_zoom, 7, "{class}");
assert_eq!(prop(&r, "min_zoom"), Some(&PropValue::I64(8)), "{class}");
}
}
#[test]
fn overture_locality_in_the_wikidata_table_takes_its_zoom_and_rank() {
let r = process(&make_overture(&[
("subtype", PropValue::Str("locality".into())),
("class", PropValue::Str("city".into())),
("population", PropValue::I64(12_442_373)),
("wikidata", PropValue::Str("Q1156".into())),
]))
.unwrap();
assert_eq!((r.min_zoom, r.max_zoom), (1, 15));
assert_eq!(prop(&r, "min_zoom"), Some(&PropValue::I64(2)));
assert_eq!(prop(&r, "population_rank"), Some(&PropValue::I64(14)));
}
#[test]
fn overture_country_in_the_wikidata_table_takes_its_zoom_range() {
let r = process(&make_overture(&[
("subtype", PropValue::Str("country".into())),
("wikidata", PropValue::Str("Q668".into())),
]))
.unwrap();
assert_eq!((r.min_zoom, r.max_zoom), (1, 6));
}
#[test]
fn wikidata_rows_read_as_protomaps_reads_them() {
let india = wikidata_zoom("Q668").unwrap();
assert_eq!(
(india.min_zoom, india.max_zoom, india.rank_max),
(1, Some(6), None)
);
let mumbai = wikidata_zoom("Q1156").unwrap();
assert_eq!(
(mumbai.min_zoom, mumbai.max_zoom, mumbai.rank_max),
(1, None, Some(14))
);
let delhi = wikidata_zoom("Q1353").unwrap();
assert_eq!(
(delhi.min_zoom, delhi.max_zoom, delhi.rank_max),
(3, None, Some(14))
);
assert!(wikidata_zoom("Q0").is_none());
}
#[test]
fn every_wikidata_row_parses() {
let rows: Vec<&str> = WIKIDATA_CSV.lines().skip(1).collect();
assert_eq!(rows.len(), 7542);
for row in rows {
assert!(parse_wikidata_row(row).is_some(), "{row}");
}
}
#[test]
fn overture_hood_subtypes_are_kept() {
let cases = [
("macrohood", "macrohood", 11u8),
("neighborhood", "neighbourhood", 12),
("microhood", "neighbourhood", 13),
("dependency", "country", 5),
];
for (subtype, kind, zoom) in cases {
let r = process(&make_overture(&[(
"subtype",
PropValue::Str(subtype.into()),
)]))
.unwrap();
assert_eq!(
prop(&r, "kind"),
Some(&PropValue::Str(kind.into())),
"{subtype}"
);
assert_eq!(r.min_zoom, zoom, "{subtype}");
}
}
fn has(r: &ProcessedFeature, key: &str, value: &str) -> bool {
r.properties
.iter()
.any(|(k, v)| k == key && *v == PropValue::Str(value.into()))
}
#[test]
fn osm_city_carries_the_names_the_style_reads() {
let r = process(&make_osm(&[
("place", "city"),
("name", "کراچی"),
("name:en", "Karachi"),
("name:ur", "کراچی"),
("name:xx", "dropped"),
]))
.unwrap();
assert!(has(&r, "name", "کراچی"));
assert!(has(&r, "script", "Arabic"));
assert!(has(&r, "name:en", "Karachi"));
assert!(has(&r, "name:ur", "کراچی"));
assert!(r.properties.iter().all(|(k, _)| k != "name:xx"));
}
#[test]
fn overture_country_carries_name_en_for_the_country_label() {
let r = process(&make_overture(&[
("subtype", PropValue::Str("country".into())),
("names.primary", PropValue::Str("پاکستان".into())),
("names.common.en", PropValue::Str("Pakistan".into())),
]))
.unwrap();
assert!(has(&r, "name", "پاکستان"));
assert!(has(&r, "script", "Arabic"));
assert!(has(&r, "name:en", "Pakistan"));
}
#[test]
fn overture_localadmin_is_not_a_place() {
let localadmin = [("subtype", PropValue::Str("localadmin".into()))];
let unknown = [("subtype", PropValue::Str("unknown".into()))];
for props in [&localadmin[..], &unknown, &[]] {
assert!(process(&make_overture(props)).is_none(), "{props:?}");
}
}
#[test]
fn population_rank_function() {
assert_eq!(population_rank(1_000_000_000), 18);
assert_eq!(population_rank(100_000_000), 17);
assert_eq!(population_rank(5_000_000), 13);
assert_eq!(population_rank(1_000_000), 12);
assert_eq!(population_rank(500), 2);
assert_eq!(population_rank(200), 2);
assert_eq!(population_rank(100), 1);
assert_eq!(population_rank(0), 1);
}
#[test]
fn osm_country_kind_and_zoom() {
let feat = make_osm(&[("place", "country"), ("name", "France")]);
let result = process(&feat).unwrap();
assert_eq!(result.layer, Layer::Places);
assert_eq!(result.min_zoom, 5);
assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(6)));
assert_eq!(result.max_zoom, 8);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
);
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind_detail" && *v == PropValue::Str("country".into()))
);
}
#[test]
fn osm_city_with_population() {
let feat = make_osm(&[
("place", "city"),
("name", "Paris"),
("population", "2161000"),
]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 7);
assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(8)));
assert_eq!(result.max_zoom, 15);
let pop = result
.properties
.iter()
.find(|(k, _)| k == "population")
.map(|(_, v)| v.clone());
assert_eq!(pop, Some(PropValue::I64(2_161_000)));
}
#[test]
fn osm_city_without_population_gets_default() {
let feat = make_osm(&[("place", "city"), ("name", "Smallville")]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 8); let pop = result
.properties
.iter()
.find(|(k, _)| k == "population")
.map(|(_, v)| v.clone());
assert_eq!(pop, Some(PropValue::I64(5000)));
}
#[test]
fn osm_hamlet_default_population() {
let feat = make_osm(&[("place", "hamlet"), ("name", "Tiny")]);
let result = process(&feat).unwrap();
assert_eq!(result.min_zoom, 12); let pop = result
.properties
.iter()
.find(|(k, _)| k == "population")
.map(|(_, v)| v.clone());
assert_eq!(pop, Some(PropValue::I64(200)));
}
#[test]
fn osm_state_in_us_is_region() {
let feat = make_osm(&[
("place", "state"),
("name", "California"),
("ISO3166-1:alpha2", "US"),
]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
);
assert_eq!(result.min_zoom, 8);
}
#[test]
fn osm_state_outside_major_countries_skipped() {
let feat = make_osm(&[
("place", "state"),
("name", "Bayern"),
("ISO3166-1:alpha2", "DE"),
]);
assert!(process(&feat).is_none());
}
#[test]
fn osm_suburb_is_neighbourhood() {
let feat = make_osm(&[("place", "suburb"), ("name", "Montmartre")]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("neighbourhood".into()))
);
assert_eq!(result.min_zoom, 11);
}
#[test]
fn osm_quarter_is_macrohood() {
let feat = make_osm(&[("place", "quarter"), ("name", "Latin Quarter")]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "kind" && *v == PropValue::Str("macrohood".into()))
);
assert_eq!(result.min_zoom, 10);
}
#[test]
fn osm_capital_extracted() {
let feat = make_osm(&[
("place", "city"),
("name", "Delhi"),
("capital", "yes"),
("population", "11000000"),
]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "capital" && *v == PropValue::Str("yes".into()))
);
}
#[test]
fn osm_wikidata_extracted() {
let feat = make_osm(&[
("place", "city"),
("name", "Paris"),
("wikidata", "Q90"),
("population", "2161000"),
]);
let result = process(&feat).unwrap();
assert!(
result
.properties
.iter()
.any(|(k, v)| k == "wikidata" && *v == PropValue::Str("Q90".into()))
);
}
#[test]
fn osm_places_in_the_wikidata_table_take_their_zooms() {
let city = process(&make_osm(&[
("place", "city"),
("name", "Mumbai"),
("population", "12442373"),
("wikidata", "Q1156"),
]))
.unwrap();
assert_eq!((city.min_zoom, city.max_zoom), (1, 15));
assert_eq!(prop(&city, "min_zoom"), Some(&PropValue::I64(2)));
assert_eq!(prop(&city, "population_rank"), Some(&PropValue::I64(14)));
let country = process(&make_osm(&[
("place", "country"),
("name", "India"),
("wikidata", "Q668"),
]))
.unwrap();
assert_eq!((country.min_zoom, country.max_zoom), (1, 6));
}
#[test]
fn osm_unknown_place_returns_none() {
let feat = make_osm(&[("place", "ocean")]);
assert!(process(&feat).is_none());
}
#[test]
fn osm_non_point_skipped() {
let mut properties = HashMap::new();
properties.insert("place".to_string(), PropValue::Str("city".to_string()));
let feat = InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]),
vec![],
))),
properties,
bbox: None,
source: DataSource::Osm {
element_type: OsmElementType::Way,
relations: vec![],
},
};
assert!(process(&feat).is_none());
}
#[test]
fn osm_population_with_comma() {
let feat = make_osm(&[
("place", "city"),
("name", "Bogota"),
("population", "7,181,469"),
]);
let result = process(&feat).unwrap();
let pop = result
.properties
.iter()
.find(|(k, _)| k == "population")
.map(|(_, v)| v.clone());
assert_eq!(pop, Some(PropValue::I64(7_181_469)));
}
#[test]
fn ne_source_returns_none() {
let feat = InputFeature {
id: 1,
geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
properties: HashMap::new(),
bbox: None,
source: DataSource::NaturalEarth {
source_layer: "ne_10m_populated_places".to_string(),
},
};
assert!(process(&feat).is_none());
}
}