Skip to main content

geolith_tiles_builder/layers/
places.rs

1//! Places layer — country, city, town, village labels.
2//!
3//! Processes features from multiple data sources:
4//! - **Overture**: `divisions/division` features with subtype mapping
5//! - **OSM**: `place=*` tags with 12 place types, population defaults, capital
6
7use std::collections::HashMap;
8use std::sync::OnceLock;
9
10use geolith::names::push_names;
11
12use crate::layers::{Layer, mark_foreign};
13use crate::source::input::{DataSource, InputFeature};
14use crate::tile::feature::PropValue;
15
16use super::buildings::ProcessedFeature;
17
18/// Zoom overrides per Wikidata id: protomaps basemaps `places.csv` at
19/// commit `cf87de9f`, unchanged (BSD-3-Clause, see
20/// `places-wikidata.LICENSE`). Columns: `wikidata,minzoom,maxzoom,rankmax`;
21/// `-1` means not set. It is what puts countries and large cities on the map
22/// from z1–z6, as in protomaps `Places.getZoomsPops`.
23const WIKIDATA_CSV: &str = include_str!("places-wikidata.csv");
24
25/// One row of [`WIKIDATA_CSV`].
26#[derive(Debug, Clone, Copy)]
27struct WikidataZoom {
28    /// Zoom range start.
29    min_zoom: u8,
30    /// Zoom range end, for countries and regions.
31    max_zoom: Option<u8>,
32    /// Population rank, for localities.
33    rank_max: Option<u8>,
34}
35
36/// Parse one `wikidata,minzoom,maxzoom,rankmax` row.
37fn parse_wikidata_row(row: &str) -> Option<(&str, WikidataZoom)> {
38    let mut columns = row.split(',');
39    let id = columns.next()?;
40    let mut number = || columns.next()?.trim().parse::<i16>().ok();
41    let (min_zoom, max_zoom, rank_max) = (number()?, number()?, number()?);
42    Some((
43        id,
44        WikidataZoom {
45            min_zoom: u8::try_from(min_zoom).ok()?,
46            max_zoom: u8::try_from(max_zoom).ok(),
47            rank_max: u8::try_from(rank_max).ok(),
48        },
49    ))
50}
51
52/// The row for a Wikidata id. A later row for the same id wins, as in
53/// protomaps (`HashMap.put`).
54fn wikidata_zoom(id: &str) -> Option<WikidataZoom> {
55    static TABLE: OnceLock<HashMap<&'static str, WikidataZoom>> = OnceLock::new();
56    TABLE
57        .get_or_init(|| {
58            WIKIDATA_CSV
59                .lines()
60                .skip(1)
61                .filter_map(parse_wikidata_row)
62                .collect()
63        })
64        .get(id)
65        .copied()
66}
67
68/// Zoom range and population rank after the Wikidata override.
69struct Zooms {
70    min_zoom: u8,
71    max_zoom: u8,
72    population_rank: Option<u8>,
73}
74
75/// Apply the [`WIKIDATA_CSV`] row, as protomaps `Places.getZoomsPops`:
76/// countries and regions take its zoom range, localities its min zoom and
77/// population rank.
78fn apply_wikidata(kind: &str, wikidata: Option<&str>, zooms: Zooms) -> Zooms {
79    let Some(row) = wikidata.and_then(wikidata_zoom) else {
80        return zooms;
81    };
82    match kind {
83        "country" | "region" => Zooms {
84            min_zoom: row.min_zoom,
85            max_zoom: row.max_zoom.unwrap_or(zooms.max_zoom),
86            ..zooms
87        },
88        "locality" => Zooms {
89            min_zoom: row.min_zoom,
90            population_rank: row.rank_max.or(zooms.population_rank),
91            ..zooms
92        },
93        _ => zooms,
94    }
95}
96
97/// Population break points for rank calculation.
98///
99/// Rank is determined by finding the first threshold the population meets
100/// or exceeds. Higher rank = more prominent place.
101const POP_BREAKS: &[u64] = &[
102    1_000_000_000,
103    100_000_000,
104    50_000_000,
105    20_000_000,
106    10_000_000,
107    5_000_000,
108    1_000_000,
109    500_000,
110    200_000,
111    100_000,
112    50_000,
113    20_000,
114    10_000,
115    5_000,
116    2_000,
117    1_000,
118    200,
119    0,
120];
121
122/// Countries where state/province gets region classification.
123const REGION_COUNTRIES: &[&str] = &["US", "CA", "BR", "IN", "CN", "AU"];
124
125/// Calculate population rank from an absolute population value.
126///
127/// Returns a rank from 0 (smallest) to 18 (largest, >= 1 billion).
128fn population_rank(population: u64) -> u8 {
129    for (i, &threshold) in POP_BREAKS.iter().enumerate() {
130        if population >= threshold {
131            return (POP_BREAKS.len() - i) as u8;
132        }
133    }
134    0
135}
136
137/// Process a feature into a places layer feature.
138///
139/// Routes to the appropriate handler based on data source.
140pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
141    match &feature.source {
142        DataSource::Overture { .. } => process_overture(feature),
143        DataSource::Osm { .. } => process_osm(feature),
144        _ => None,
145    }
146}
147
148/// Process an Overture divisions/division feature.
149///
150/// Localities take their zoom from `class`: cities and towns at z7 as in
151/// protomaps `Places.zoomsIndex` (z8 and z9 without a population), villages
152/// at z12, hamlets at z13, others at z10. A flat z10 put all 3.25M villages
153/// and hamlets in the release on screen at z10. `macrohood` and `microhood`
154/// map to the protomaps `macrohood` and `neighbourhood` kinds, as in
155/// protomaps `Places.processOverture`. A row in [`WIKIDATA_CSV`] overrides
156/// the zoom; the `min_zoom` attribute is the range start plus one, as in
157/// protomaps.
158fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
159    let subtype = feature.get_str("subtype")?;
160    let class = feature.get_str("class");
161    let population = feature.get_i64("population");
162    let has_population = population.is_some_and(|p| p > 0);
163
164    let (kind, min_zoom) = match subtype {
165        "country" | "dependency" => ("country", 5u8),
166        "region" => ("region", 8),
167        "county" => ("county", 7),
168        "locality" => match class {
169            Some("city") => ("locality", if has_population { 7 } else { 8 }),
170            Some("town") => ("locality", if has_population { 7 } else { 9 }),
171            Some("village") => ("locality", 12),
172            Some("hamlet") => ("locality", 13),
173            _ => ("locality", 10),
174        },
175        "macrohood" => ("macrohood", 11),
176        "neighbourhood" | "neighborhood" => ("neighbourhood", 12),
177        "microhood" => ("neighbourhood", 13),
178        _ => return None,
179    };
180
181    let zooms = apply_wikidata(
182        kind,
183        feature.get_str("wikidata"),
184        Zooms {
185            min_zoom,
186            max_zoom: 15,
187            population_rank: population.map(|p| population_rank(p.max(0) as u64)),
188        },
189    );
190
191    let mut properties = Vec::with_capacity(7);
192    properties.push(("kind".into(), PropValue::Str(kind.into())));
193    if let Some(class) = class {
194        properties.push(("kind_detail".into(), PropValue::Str(class.to_string())));
195    }
196
197    if let Some(pop) = population {
198        properties.push(("population".into(), PropValue::I64(pop)));
199    }
200    if let Some(rank) = zooms.population_rank {
201        properties.push(("population_rank".into(), PropValue::I64(i64::from(rank))));
202    }
203
204    push_names(feature, &mut properties);
205
206    properties.push(("class".into(), PropValue::Str(kind.into())));
207
208    if let Some(wikidata) = feature.get_str("wikidata") {
209        properties.push(("wikidata".into(), PropValue::Str(wikidata.to_string())));
210    }
211
212    properties.push((
213        "min_zoom".into(),
214        PropValue::I64(i64::from(zooms.min_zoom) + 1),
215    ));
216    // The label of an admin area that is not India's (a Pakistani division,
217    // a Chinese prefecture, Overture's claim record "South Tibet") is
218    // dropped by the Survey of India mask where it lies on India's land.
219    if geolith::admin::soi_area::is_foreign_admin_area(
220        subtype,
221        feature.get_str("country"),
222        feature.get_str("region"),
223    ) {
224        mark_foreign(&mut properties);
225    }
226
227    Some(ProcessedFeature {
228        id: feature.id,
229        geometry: feature.geometry.clone(),
230        layer: Layer::Places,
231        min_zoom: zooms.min_zoom,
232        max_zoom: zooms.max_zoom,
233        sort_rank: 300,
234        properties,
235    })
236}
237
238/// OSM place classification result.
239struct PlaceClass {
240    /// Output kind value.
241    kind: &'static str,
242    /// Zoom range start (the `min_zoom` attribute is this plus one).
243    min_zoom: u8,
244    /// Maximum zoom level.
245    max_zoom: u8,
246    /// Kind rank for sort ordering.
247    kind_rank: u8,
248    /// Default population when tag is missing.
249    default_pop: Option<u64>,
250}
251
252/// Classify an OSM place tag value.
253///
254/// Returns classification details or `None` for unknown place types.
255/// For state/province, `country_code` is checked against `REGION_COUNTRIES`.
256fn classify_place(place: &str, country_code: Option<&str>) -> Option<PlaceClass> {
257    match place {
258        "country" => Some(PlaceClass {
259            kind: "country",
260            min_zoom: 5,
261            max_zoom: 8,
262            kind_rank: 0,
263            default_pop: None,
264        }),
265        "state" | "province" => {
266            let is_major = country_code
267                .is_some_and(|cc| REGION_COUNTRIES.iter().any(|r| cc.eq_ignore_ascii_case(r)));
268            if is_major {
269                Some(PlaceClass {
270                    kind: "region",
271                    min_zoom: 8,
272                    max_zoom: 11,
273                    kind_rank: 1,
274                    default_pop: None,
275                })
276            } else {
277                None
278            }
279        }
280        "city" => Some(PlaceClass {
281            kind: "locality",
282            min_zoom: 7,
283            max_zoom: 15,
284            kind_rank: 2,
285            default_pop: Some(5000),
286        }),
287        "town" => Some(PlaceClass {
288            kind: "locality",
289            min_zoom: 7,
290            max_zoom: 15,
291            kind_rank: 2,
292            default_pop: Some(10_000),
293        }),
294        "village" => Some(PlaceClass {
295            kind: "locality",
296            min_zoom: 10,
297            max_zoom: 15,
298            kind_rank: 3,
299            default_pop: Some(2000),
300        }),
301        "locality" => Some(PlaceClass {
302            kind: "locality",
303            min_zoom: 11,
304            max_zoom: 15,
305            kind_rank: 4,
306            default_pop: Some(1000),
307        }),
308        "hamlet" => Some(PlaceClass {
309            kind: "locality",
310            min_zoom: 11,
311            max_zoom: 15,
312            kind_rank: 5,
313            default_pop: Some(200),
314        }),
315        "isolated_dwelling" => Some(PlaceClass {
316            kind: "locality",
317            min_zoom: 13,
318            max_zoom: 15,
319            kind_rank: 6,
320            default_pop: Some(100),
321        }),
322        "farm" => Some(PlaceClass {
323            kind: "locality",
324            min_zoom: 13,
325            max_zoom: 15,
326            kind_rank: 7,
327            default_pop: Some(50),
328        }),
329        "allotments" => Some(PlaceClass {
330            kind: "locality",
331            min_zoom: 13,
332            max_zoom: 15,
333            kind_rank: 8,
334            default_pop: Some(1000),
335        }),
336        "suburb" => Some(PlaceClass {
337            kind: "neighbourhood",
338            min_zoom: 11,
339            max_zoom: 15,
340            kind_rank: 9,
341            default_pop: None,
342        }),
343        "quarter" => Some(PlaceClass {
344            kind: "macrohood",
345            min_zoom: 10,
346            max_zoom: 15,
347            kind_rank: 10,
348            default_pop: None,
349        }),
350        "neighbourhood" | "neighborhood" => Some(PlaceClass {
351            kind: "neighbourhood",
352            min_zoom: 12,
353            max_zoom: 15,
354            kind_rank: 11,
355            default_pop: None,
356        }),
357        _ => None,
358    }
359}
360
361/// Process OSM `place=*` features.
362///
363/// Spec §8: 12 place types with population defaults, capital detection,
364/// wikidata. As in protomaps `Places.processOsm`, the zoom range starts at
365/// the spec min zoom (or the [`WIKIDATA_CSV`] row) and the `min_zoom`
366/// attribute is that plus one.
367fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
368    let place = feature.get_str("place")?;
369
370    if !feature.is_point() {
371        return None;
372    }
373
374    let country_code = feature
375        .get_str("addr:country")
376        .or(feature.get_str("is_in:country_code"))
377        .or(feature.get_str("ISO3166-1:alpha2"));
378
379    let class = classify_place(place, country_code)?;
380
381    // Parse population from tag, fall back to default
382    let population = feature
383        .get_str("population")
384        .and_then(|s| s.replace(',', "").parse::<u64>().ok())
385        .or(feature.get_i64("population").map(|v| v.max(0) as u64))
386        .or(class.default_pop);
387
388    // Adjust zoom for cities/towns without population
389    let has_explicit_pop = feature.has_key("population");
390    let adjusted_min_zoom = if !has_explicit_pop && class.default_pop.is_some() {
391        match place {
392            "city" => 8u8,
393            "town" => 9,
394            "village" => 11,
395            "locality" => 12,
396            "hamlet" => 12,
397            "isolated_dwelling" | "farm" | "allotments" => 14,
398            _ => class.min_zoom,
399        }
400    } else {
401        class.min_zoom
402    };
403
404    let zooms = apply_wikidata(
405        class.kind,
406        feature.get_str("wikidata"),
407        Zooms {
408            min_zoom: adjusted_min_zoom,
409            max_zoom: class.max_zoom,
410            population_rank: population.map(population_rank),
411        },
412    );
413
414    let sort_rank = 300 + i32::from(class.kind_rank);
415
416    let mut properties = Vec::with_capacity(8);
417    properties.push(("kind".into(), PropValue::Str(class.kind.into())));
418    properties.push(("kind_detail".into(), PropValue::Str(place.to_string())));
419
420    if let Some(pop) = population {
421        properties.push(("population".into(), PropValue::I64(pop as i64)));
422    }
423    if let Some(rank) = zooms.population_rank {
424        properties.push(("population_rank".into(), PropValue::I64(i64::from(rank))));
425    }
426
427    if let Some(capital) = feature.get_str("capital") {
428        properties.push(("capital".into(), PropValue::Str(capital.to_string())));
429    }
430
431    if let Some(wikidata) = feature.get_str("wikidata") {
432        properties.push(("wikidata".into(), PropValue::Str(wikidata.to_string())));
433    }
434
435    push_names(feature, &mut properties);
436
437    properties.push((
438        "min_zoom".into(),
439        PropValue::I64(i64::from(zooms.min_zoom) + 1),
440    ));
441
442    Some(ProcessedFeature {
443        id: feature.id,
444        geometry: feature.geometry.clone(),
445        layer: Layer::Places,
446        min_zoom: zooms.min_zoom,
447        max_zoom: zooms.max_zoom,
448        sort_rank,
449        properties,
450    })
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    use crate::source::input::{DataSource, OsmElementType};
457    use std::collections::HashMap;
458    use std::sync::Arc;
459
460    fn make_overture(props: &[(&str, PropValue)]) -> InputFeature {
461        let mut properties = HashMap::new();
462        for (k, v) in props {
463            properties.insert(k.to_string(), v.clone());
464        }
465        InputFeature {
466            id: 1,
467            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(2.35, 48.86))),
468            properties,
469            bbox: None,
470            source: DataSource::Overture {
471                theme: String::new(),
472                otype: String::new(),
473            },
474        }
475    }
476
477    fn make_osm(tags: &[(&str, &str)]) -> InputFeature {
478        let mut properties = HashMap::new();
479        for (k, v) in tags {
480            properties.insert(k.to_string(), PropValue::Str(v.to_string()));
481        }
482        InputFeature {
483            id: 42,
484            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(2.35, 48.86))),
485            properties,
486            bbox: None,
487            source: DataSource::Osm {
488                element_type: OsmElementType::Node,
489                relations: vec![],
490            },
491        }
492    }
493
494    #[test]
495    fn overture_country_has_correct_kind_and_zoom() {
496        let feat = make_overture(&[("subtype", PropValue::Str("country".into()))]);
497        let result = process(&feat).unwrap();
498        assert_eq!(result.layer, Layer::Places);
499        assert_eq!(result.min_zoom, 5);
500        assert_eq!(result.sort_rank, 300);
501        assert!(
502            result
503                .properties
504                .iter()
505                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
506        );
507    }
508
509    #[test]
510    fn overture_locality_without_class_starts_at_zoom_10() {
511        let feat = make_overture(&[("subtype", PropValue::Str("locality".into()))]);
512        let result = process(&feat).unwrap();
513        assert_eq!(result.min_zoom, 10);
514        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(11)));
515    }
516
517    #[test]
518    fn overture_population_rank_calculated() {
519        let feat = make_overture(&[
520            ("subtype", PropValue::Str("locality".into())),
521            ("population", PropValue::I64(5_000_000)),
522        ]);
523        let result = process(&feat).unwrap();
524        let rank = result
525            .properties
526            .iter()
527            .find(|(k, _)| k == "population_rank")
528            .map(|(_, v)| v.clone());
529        assert_eq!(rank, Some(PropValue::I64(13)));
530    }
531
532    fn prop<'a>(r: &'a ProcessedFeature, key: &str) -> Option<&'a PropValue> {
533        r.properties.iter().find(|(k, _)| k == key).map(|(_, v)| v)
534    }
535
536    /// (subtype, class) pairs from the 2026-08-19.0 release. Cities and towns
537    /// without a population follow protomaps `Places.zoomsIndex`: city 8,
538    /// town 9 (`pm:populationFallback`).
539    #[test]
540    fn overture_locality_zoom_follows_class() {
541        let cases = [
542            (Some("city"), 8u8),
543            (Some("town"), 9),
544            (None, 10),
545            (Some("village"), 12),
546            (Some("hamlet"), 13),
547        ];
548        for (class, zoom) in cases {
549            let mut props = vec![("subtype", PropValue::Str("locality".into()))];
550            if let Some(c) = class {
551                props.push(("class", PropValue::Str(c.into())));
552            }
553            let r = process(&make_overture(&props)).unwrap();
554            assert_eq!(
555                prop(&r, "kind"),
556                Some(&PropValue::Str("locality".into())),
557                "{class:?}"
558            );
559            assert_eq!(r.min_zoom, zoom, "{class:?}");
560            assert_eq!(
561                prop(&r, "kind_detail"),
562                class.map(|c| PropValue::Str(c.into())).as_ref(),
563                "{class:?}"
564            );
565        }
566    }
567
568    /// protomaps `Places.zoomsIndex`: a city or town with a population starts
569    /// at z7; the `min_zoom` attribute is the zoom range start plus one.
570    #[test]
571    fn overture_city_and_town_with_population_start_at_zoom_7() {
572        for class in ["city", "town"] {
573            let r = process(&make_overture(&[
574                ("subtype", PropValue::Str("locality".into())),
575                ("class", PropValue::Str(class.into())),
576                ("population", PropValue::I64(250_000)),
577            ]))
578            .unwrap();
579            assert_eq!(r.min_zoom, 7, "{class}");
580            assert_eq!(prop(&r, "min_zoom"), Some(&PropValue::I64(8)), "{class}");
581        }
582    }
583
584    /// Mumbai (Q1156) is `Q1156,1,-1,14` in places-wikidata.csv: a locality
585    /// takes min zoom 1 and population rank 14 from the row.
586    #[test]
587    fn overture_locality_in_the_wikidata_table_takes_its_zoom_and_rank() {
588        let r = process(&make_overture(&[
589            ("subtype", PropValue::Str("locality".into())),
590            ("class", PropValue::Str("city".into())),
591            ("population", PropValue::I64(12_442_373)),
592            ("wikidata", PropValue::Str("Q1156".into())),
593        ]))
594        .unwrap();
595        assert_eq!((r.min_zoom, r.max_zoom), (1, 15));
596        assert_eq!(prop(&r, "min_zoom"), Some(&PropValue::I64(2)));
597        assert_eq!(prop(&r, "population_rank"), Some(&PropValue::I64(14)));
598    }
599
600    /// India (Q668) is `Q668,1,6,-1`: a country takes min and max zoom.
601    #[test]
602    fn overture_country_in_the_wikidata_table_takes_its_zoom_range() {
603        let r = process(&make_overture(&[
604            ("subtype", PropValue::Str("country".into())),
605            ("wikidata", PropValue::Str("Q668".into())),
606        ]))
607        .unwrap();
608        assert_eq!((r.min_zoom, r.max_zoom), (1, 6));
609    }
610
611    /// Rows read by eye from places-wikidata.csv (protomaps `cf87de9f`).
612    #[test]
613    fn wikidata_rows_read_as_protomaps_reads_them() {
614        let india = wikidata_zoom("Q668").unwrap();
615        assert_eq!(
616            (india.min_zoom, india.max_zoom, india.rank_max),
617            (1, Some(6), None)
618        );
619        let mumbai = wikidata_zoom("Q1156").unwrap();
620        assert_eq!(
621            (mumbai.min_zoom, mumbai.max_zoom, mumbai.rank_max),
622            (1, None, Some(14))
623        );
624        // Delhi (Q1353) has two rows, `4,9,-1` then `3,-1,14`. The later row
625        // wins, as protomaps' `HashMap.put` does.
626        let delhi = wikidata_zoom("Q1353").unwrap();
627        assert_eq!(
628            (delhi.min_zoom, delhi.max_zoom, delhi.rank_max),
629            (3, None, Some(14))
630        );
631        assert!(wikidata_zoom("Q0").is_none());
632    }
633
634    /// The file has 7,542 data rows; a row that does not parse would be
635    /// dropped without a word.
636    #[test]
637    fn every_wikidata_row_parses() {
638        let rows: Vec<&str> = WIKIDATA_CSV.lines().skip(1).collect();
639        assert_eq!(rows.len(), 7542);
640        for row in rows {
641            assert!(parse_wikidata_row(row).is_some(), "{row}");
642        }
643    }
644
645    #[test]
646    fn overture_hood_subtypes_are_kept() {
647        let cases = [
648            ("macrohood", "macrohood", 11u8),
649            ("neighborhood", "neighbourhood", 12),
650            ("microhood", "neighbourhood", 13),
651            ("dependency", "country", 5),
652        ];
653        for (subtype, kind, zoom) in cases {
654            let r = process(&make_overture(&[(
655                "subtype",
656                PropValue::Str(subtype.into()),
657            )]))
658            .unwrap();
659            assert_eq!(
660                prop(&r, "kind"),
661                Some(&PropValue::Str(kind.into())),
662                "{subtype}"
663            );
664            assert_eq!(r.min_zoom, zoom, "{subtype}");
665        }
666    }
667
668    fn has(r: &ProcessedFeature, key: &str, value: &str) -> bool {
669        r.properties
670            .iter()
671            .any(|(k, v)| k == key && *v == PropValue::Str(value.into()))
672    }
673
674    #[test]
675    fn osm_city_carries_the_names_the_style_reads() {
676        let r = process(&make_osm(&[
677            ("place", "city"),
678            ("name", "کراچی"),
679            ("name:en", "Karachi"),
680            ("name:ur", "کراچی"),
681            ("name:xx", "dropped"),
682        ]))
683        .unwrap();
684        assert!(has(&r, "name", "کراچی"));
685        assert!(has(&r, "script", "Arabic"));
686        assert!(has(&r, "name:en", "Karachi"));
687        assert!(has(&r, "name:ur", "کراچی"));
688        assert!(r.properties.iter().all(|(k, _)| k != "name:xx"));
689    }
690
691    #[test]
692    fn overture_country_carries_name_en_for_the_country_label() {
693        // `get_country_name` reads `name:<lang>` and `name:en` only.
694        let r = process(&make_overture(&[
695            ("subtype", PropValue::Str("country".into())),
696            ("names.primary", PropValue::Str("پاکستان".into())),
697            ("names.common.en", PropValue::Str("Pakistan".into())),
698        ]))
699        .unwrap();
700        assert!(has(&r, "name", "پاکستان"));
701        assert!(has(&r, "script", "Arabic"));
702        assert!(has(&r, "name:en", "Pakistan"));
703    }
704
705    #[test]
706    fn overture_localadmin_is_not_a_place() {
707        // Nor is a missing or an unknown subtype.
708        let localadmin = [("subtype", PropValue::Str("localadmin".into()))];
709        let unknown = [("subtype", PropValue::Str("unknown".into()))];
710        for props in [&localadmin[..], &unknown, &[]] {
711            assert!(process(&make_overture(props)).is_none(), "{props:?}");
712        }
713    }
714
715    #[test]
716    fn population_rank_function() {
717        assert_eq!(population_rank(1_000_000_000), 18);
718        assert_eq!(population_rank(100_000_000), 17);
719        assert_eq!(population_rank(5_000_000), 13);
720        assert_eq!(population_rank(1_000_000), 12);
721        assert_eq!(population_rank(500), 2);
722        assert_eq!(population_rank(200), 2);
723        assert_eq!(population_rank(100), 1);
724        assert_eq!(population_rank(0), 1);
725    }
726
727    #[test]
728    fn osm_country_kind_and_zoom() {
729        let feat = make_osm(&[("place", "country"), ("name", "France")]);
730        let result = process(&feat).unwrap();
731        assert_eq!(result.layer, Layer::Places);
732        // protomaps: zoom range starts at 5, the attribute is 5 + 1.
733        assert_eq!(result.min_zoom, 5);
734        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(6)));
735        assert_eq!(result.max_zoom, 8);
736        assert!(
737            result
738                .properties
739                .iter()
740                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
741        );
742        assert!(
743            result
744                .properties
745                .iter()
746                .any(|(k, v)| k == "kind_detail" && *v == PropValue::Str("country".into()))
747        );
748    }
749
750    #[test]
751    fn osm_city_with_population() {
752        let feat = make_osm(&[
753            ("place", "city"),
754            ("name", "Paris"),
755            ("population", "2161000"),
756        ]);
757        let result = process(&feat).unwrap();
758        assert_eq!(result.min_zoom, 7);
759        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(8)));
760        assert_eq!(result.max_zoom, 15);
761        let pop = result
762            .properties
763            .iter()
764            .find(|(k, _)| k == "population")
765            .map(|(_, v)| v.clone());
766        assert_eq!(pop, Some(PropValue::I64(2_161_000)));
767    }
768
769    #[test]
770    fn osm_city_without_population_gets_default() {
771        let feat = make_osm(&[("place", "city"), ("name", "Smallville")]);
772        let result = process(&feat).unwrap();
773        assert_eq!(result.min_zoom, 8); // no population: city starts at 8
774        let pop = result
775            .properties
776            .iter()
777            .find(|(k, _)| k == "population")
778            .map(|(_, v)| v.clone());
779        assert_eq!(pop, Some(PropValue::I64(5000)));
780    }
781
782    #[test]
783    fn osm_hamlet_default_population() {
784        let feat = make_osm(&[("place", "hamlet"), ("name", "Tiny")]);
785        let result = process(&feat).unwrap();
786        assert_eq!(result.min_zoom, 12); // no population: hamlet starts at 12
787        let pop = result
788            .properties
789            .iter()
790            .find(|(k, _)| k == "population")
791            .map(|(_, v)| v.clone());
792        assert_eq!(pop, Some(PropValue::I64(200)));
793    }
794
795    #[test]
796    fn osm_state_in_us_is_region() {
797        let feat = make_osm(&[
798            ("place", "state"),
799            ("name", "California"),
800            ("ISO3166-1:alpha2", "US"),
801        ]);
802        let result = process(&feat).unwrap();
803        assert!(
804            result
805                .properties
806                .iter()
807                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
808        );
809        assert_eq!(result.min_zoom, 8);
810    }
811
812    #[test]
813    fn osm_state_outside_major_countries_skipped() {
814        let feat = make_osm(&[
815            ("place", "state"),
816            ("name", "Bayern"),
817            ("ISO3166-1:alpha2", "DE"),
818        ]);
819        assert!(process(&feat).is_none());
820    }
821
822    #[test]
823    fn osm_suburb_is_neighbourhood() {
824        let feat = make_osm(&[("place", "suburb"), ("name", "Montmartre")]);
825        let result = process(&feat).unwrap();
826        assert!(
827            result
828                .properties
829                .iter()
830                .any(|(k, v)| k == "kind" && *v == PropValue::Str("neighbourhood".into()))
831        );
832        assert_eq!(result.min_zoom, 11);
833    }
834
835    #[test]
836    fn osm_quarter_is_macrohood() {
837        let feat = make_osm(&[("place", "quarter"), ("name", "Latin Quarter")]);
838        let result = process(&feat).unwrap();
839        assert!(
840            result
841                .properties
842                .iter()
843                .any(|(k, v)| k == "kind" && *v == PropValue::Str("macrohood".into()))
844        );
845        assert_eq!(result.min_zoom, 10);
846    }
847
848    #[test]
849    fn osm_capital_extracted() {
850        let feat = make_osm(&[
851            ("place", "city"),
852            ("name", "Delhi"),
853            ("capital", "yes"),
854            ("population", "11000000"),
855        ]);
856        let result = process(&feat).unwrap();
857        assert!(
858            result
859                .properties
860                .iter()
861                .any(|(k, v)| k == "capital" && *v == PropValue::Str("yes".into()))
862        );
863    }
864
865    #[test]
866    fn osm_wikidata_extracted() {
867        let feat = make_osm(&[
868            ("place", "city"),
869            ("name", "Paris"),
870            ("wikidata", "Q90"),
871            ("population", "2161000"),
872        ]);
873        let result = process(&feat).unwrap();
874        assert!(
875            result
876                .properties
877                .iter()
878                .any(|(k, v)| k == "wikidata" && *v == PropValue::Str("Q90".into()))
879        );
880    }
881
882    /// Mumbai (`Q1156,1,-1,14`) and India (`Q668,1,6,-1`) from OSM.
883    #[test]
884    fn osm_places_in_the_wikidata_table_take_their_zooms() {
885        let city = process(&make_osm(&[
886            ("place", "city"),
887            ("name", "Mumbai"),
888            ("population", "12442373"),
889            ("wikidata", "Q1156"),
890        ]))
891        .unwrap();
892        assert_eq!((city.min_zoom, city.max_zoom), (1, 15));
893        assert_eq!(prop(&city, "min_zoom"), Some(&PropValue::I64(2)));
894        assert_eq!(prop(&city, "population_rank"), Some(&PropValue::I64(14)));
895
896        let country = process(&make_osm(&[
897            ("place", "country"),
898            ("name", "India"),
899            ("wikidata", "Q668"),
900        ]))
901        .unwrap();
902        assert_eq!((country.min_zoom, country.max_zoom), (1, 6));
903    }
904
905    #[test]
906    fn osm_unknown_place_returns_none() {
907        let feat = make_osm(&[("place", "ocean")]);
908        assert!(process(&feat).is_none());
909    }
910
911    #[test]
912    fn osm_non_point_skipped() {
913        let mut properties = HashMap::new();
914        properties.insert("place".to_string(), PropValue::Str("city".to_string()));
915        let feat = InputFeature {
916            id: 1,
917            geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
918                geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]),
919                vec![],
920            ))),
921            properties,
922            bbox: None,
923            source: DataSource::Osm {
924                element_type: OsmElementType::Way,
925                relations: vec![],
926            },
927        };
928        assert!(process(&feat).is_none());
929    }
930
931    #[test]
932    fn osm_population_with_comma() {
933        let feat = make_osm(&[
934            ("place", "city"),
935            ("name", "Bogota"),
936            ("population", "7,181,469"),
937        ]);
938        let result = process(&feat).unwrap();
939        let pop = result
940            .properties
941            .iter()
942            .find(|(k, _)| k == "population")
943            .map(|(_, v)| v.clone());
944        assert_eq!(pop, Some(PropValue::I64(7_181_469)));
945    }
946
947    #[test]
948    fn ne_source_returns_none() {
949        let feat = InputFeature {
950            id: 1,
951            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
952            properties: HashMap::new(),
953            bbox: None,
954            source: DataSource::NaturalEarth {
955                source_layer: "ne_10m_populated_places".to_string(),
956            },
957        };
958        assert!(process(&feat).is_none());
959    }
960}