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;
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
217    Some(ProcessedFeature {
218        id: feature.id,
219        geometry: feature.geometry.clone(),
220        layer: Layer::Places,
221        min_zoom: zooms.min_zoom,
222        max_zoom: zooms.max_zoom,
223        sort_rank: 300,
224        properties,
225    })
226}
227
228/// OSM place classification result.
229struct PlaceClass {
230    /// Output kind value.
231    kind: &'static str,
232    /// Zoom range start (the `min_zoom` attribute is this plus one).
233    min_zoom: u8,
234    /// Maximum zoom level.
235    max_zoom: u8,
236    /// Kind rank for sort ordering.
237    kind_rank: u8,
238    /// Default population when tag is missing.
239    default_pop: Option<u64>,
240}
241
242/// Classify an OSM place tag value.
243///
244/// Returns classification details or `None` for unknown place types.
245/// For state/province, `country_code` is checked against `REGION_COUNTRIES`.
246fn classify_place(place: &str, country_code: Option<&str>) -> Option<PlaceClass> {
247    match place {
248        "country" => Some(PlaceClass {
249            kind: "country",
250            min_zoom: 5,
251            max_zoom: 8,
252            kind_rank: 0,
253            default_pop: None,
254        }),
255        "state" | "province" => {
256            let is_major = country_code
257                .is_some_and(|cc| REGION_COUNTRIES.iter().any(|r| cc.eq_ignore_ascii_case(r)));
258            if is_major {
259                Some(PlaceClass {
260                    kind: "region",
261                    min_zoom: 8,
262                    max_zoom: 11,
263                    kind_rank: 1,
264                    default_pop: None,
265                })
266            } else {
267                None
268            }
269        }
270        "city" => Some(PlaceClass {
271            kind: "locality",
272            min_zoom: 7,
273            max_zoom: 15,
274            kind_rank: 2,
275            default_pop: Some(5000),
276        }),
277        "town" => Some(PlaceClass {
278            kind: "locality",
279            min_zoom: 7,
280            max_zoom: 15,
281            kind_rank: 2,
282            default_pop: Some(10_000),
283        }),
284        "village" => Some(PlaceClass {
285            kind: "locality",
286            min_zoom: 10,
287            max_zoom: 15,
288            kind_rank: 3,
289            default_pop: Some(2000),
290        }),
291        "locality" => Some(PlaceClass {
292            kind: "locality",
293            min_zoom: 11,
294            max_zoom: 15,
295            kind_rank: 4,
296            default_pop: Some(1000),
297        }),
298        "hamlet" => Some(PlaceClass {
299            kind: "locality",
300            min_zoom: 11,
301            max_zoom: 15,
302            kind_rank: 5,
303            default_pop: Some(200),
304        }),
305        "isolated_dwelling" => Some(PlaceClass {
306            kind: "locality",
307            min_zoom: 13,
308            max_zoom: 15,
309            kind_rank: 6,
310            default_pop: Some(100),
311        }),
312        "farm" => Some(PlaceClass {
313            kind: "locality",
314            min_zoom: 13,
315            max_zoom: 15,
316            kind_rank: 7,
317            default_pop: Some(50),
318        }),
319        "allotments" => Some(PlaceClass {
320            kind: "locality",
321            min_zoom: 13,
322            max_zoom: 15,
323            kind_rank: 8,
324            default_pop: Some(1000),
325        }),
326        "suburb" => Some(PlaceClass {
327            kind: "neighbourhood",
328            min_zoom: 11,
329            max_zoom: 15,
330            kind_rank: 9,
331            default_pop: None,
332        }),
333        "quarter" => Some(PlaceClass {
334            kind: "macrohood",
335            min_zoom: 10,
336            max_zoom: 15,
337            kind_rank: 10,
338            default_pop: None,
339        }),
340        "neighbourhood" | "neighborhood" => Some(PlaceClass {
341            kind: "neighbourhood",
342            min_zoom: 12,
343            max_zoom: 15,
344            kind_rank: 11,
345            default_pop: None,
346        }),
347        _ => None,
348    }
349}
350
351/// Process OSM `place=*` features.
352///
353/// Spec §8: 12 place types with population defaults, capital detection,
354/// wikidata. As in protomaps `Places.processOsm`, the zoom range starts at
355/// the spec min zoom (or the [`WIKIDATA_CSV`] row) and the `min_zoom`
356/// attribute is that plus one.
357fn process_osm(feature: &InputFeature) -> Option<ProcessedFeature> {
358    let place = feature.get_str("place")?;
359
360    if !feature.is_point() {
361        return None;
362    }
363
364    let country_code = feature
365        .get_str("addr:country")
366        .or(feature.get_str("is_in:country_code"))
367        .or(feature.get_str("ISO3166-1:alpha2"));
368
369    let class = classify_place(place, country_code)?;
370
371    // Parse population from tag, fall back to default
372    let population = feature
373        .get_str("population")
374        .and_then(|s| s.replace(',', "").parse::<u64>().ok())
375        .or(feature.get_i64("population").map(|v| v.max(0) as u64))
376        .or(class.default_pop);
377
378    // Adjust zoom for cities/towns without population
379    let has_explicit_pop = feature.has_key("population");
380    let adjusted_min_zoom = if !has_explicit_pop && class.default_pop.is_some() {
381        match place {
382            "city" => 8u8,
383            "town" => 9,
384            "village" => 11,
385            "locality" => 12,
386            "hamlet" => 12,
387            "isolated_dwelling" | "farm" | "allotments" => 14,
388            _ => class.min_zoom,
389        }
390    } else {
391        class.min_zoom
392    };
393
394    let zooms = apply_wikidata(
395        class.kind,
396        feature.get_str("wikidata"),
397        Zooms {
398            min_zoom: adjusted_min_zoom,
399            max_zoom: class.max_zoom,
400            population_rank: population.map(population_rank),
401        },
402    );
403
404    let sort_rank = 300 + i32::from(class.kind_rank);
405
406    let mut properties = Vec::with_capacity(8);
407    properties.push(("kind".into(), PropValue::Str(class.kind.into())));
408    properties.push(("kind_detail".into(), PropValue::Str(place.to_string())));
409
410    if let Some(pop) = population {
411        properties.push(("population".into(), PropValue::I64(pop as i64)));
412    }
413    if let Some(rank) = zooms.population_rank {
414        properties.push(("population_rank".into(), PropValue::I64(i64::from(rank))));
415    }
416
417    if let Some(capital) = feature.get_str("capital") {
418        properties.push(("capital".into(), PropValue::Str(capital.to_string())));
419    }
420
421    if let Some(wikidata) = feature.get_str("wikidata") {
422        properties.push(("wikidata".into(), PropValue::Str(wikidata.to_string())));
423    }
424
425    push_names(feature, &mut properties);
426
427    properties.push((
428        "min_zoom".into(),
429        PropValue::I64(i64::from(zooms.min_zoom) + 1),
430    ));
431
432    Some(ProcessedFeature {
433        id: feature.id,
434        geometry: feature.geometry.clone(),
435        layer: Layer::Places,
436        min_zoom: zooms.min_zoom,
437        max_zoom: zooms.max_zoom,
438        sort_rank,
439        properties,
440    })
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::source::input::{DataSource, OsmElementType};
447    use std::collections::HashMap;
448    use std::sync::Arc;
449
450    fn make_overture(props: &[(&str, PropValue)]) -> InputFeature {
451        let mut properties = HashMap::new();
452        for (k, v) in props {
453            properties.insert(k.to_string(), v.clone());
454        }
455        InputFeature {
456            id: 1,
457            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(2.35, 48.86))),
458            properties,
459            bbox: None,
460            source: DataSource::Overture {
461                theme: String::new(),
462                otype: String::new(),
463            },
464        }
465    }
466
467    fn make_osm(tags: &[(&str, &str)]) -> InputFeature {
468        let mut properties = HashMap::new();
469        for (k, v) in tags {
470            properties.insert(k.to_string(), PropValue::Str(v.to_string()));
471        }
472        InputFeature {
473            id: 42,
474            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(2.35, 48.86))),
475            properties,
476            bbox: None,
477            source: DataSource::Osm {
478                element_type: OsmElementType::Node,
479                relations: vec![],
480            },
481        }
482    }
483
484    #[test]
485    fn overture_country_has_correct_kind_and_zoom() {
486        let feat = make_overture(&[("subtype", PropValue::Str("country".into()))]);
487        let result = process(&feat).unwrap();
488        assert_eq!(result.layer, Layer::Places);
489        assert_eq!(result.min_zoom, 5);
490        assert_eq!(result.sort_rank, 300);
491        assert!(
492            result
493                .properties
494                .iter()
495                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
496        );
497    }
498
499    #[test]
500    fn overture_locality_without_class_starts_at_zoom_10() {
501        let feat = make_overture(&[("subtype", PropValue::Str("locality".into()))]);
502        let result = process(&feat).unwrap();
503        assert_eq!(result.min_zoom, 10);
504        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(11)));
505    }
506
507    #[test]
508    fn overture_population_rank_calculated() {
509        let feat = make_overture(&[
510            ("subtype", PropValue::Str("locality".into())),
511            ("population", PropValue::I64(5_000_000)),
512        ]);
513        let result = process(&feat).unwrap();
514        let rank = result
515            .properties
516            .iter()
517            .find(|(k, _)| k == "population_rank")
518            .map(|(_, v)| v.clone());
519        assert_eq!(rank, Some(PropValue::I64(13)));
520    }
521
522    fn prop<'a>(r: &'a ProcessedFeature, key: &str) -> Option<&'a PropValue> {
523        r.properties.iter().find(|(k, _)| k == key).map(|(_, v)| v)
524    }
525
526    /// (subtype, class) pairs from the 2026-08-19.0 release. Cities and towns
527    /// without a population follow protomaps `Places.zoomsIndex`: city 8,
528    /// town 9 (`pm:populationFallback`).
529    #[test]
530    fn overture_locality_zoom_follows_class() {
531        let cases = [
532            (Some("city"), 8u8),
533            (Some("town"), 9),
534            (None, 10),
535            (Some("village"), 12),
536            (Some("hamlet"), 13),
537        ];
538        for (class, zoom) in cases {
539            let mut props = vec![("subtype", PropValue::Str("locality".into()))];
540            if let Some(c) = class {
541                props.push(("class", PropValue::Str(c.into())));
542            }
543            let r = process(&make_overture(&props)).unwrap();
544            assert_eq!(
545                prop(&r, "kind"),
546                Some(&PropValue::Str("locality".into())),
547                "{class:?}"
548            );
549            assert_eq!(r.min_zoom, zoom, "{class:?}");
550            assert_eq!(
551                prop(&r, "kind_detail"),
552                class.map(|c| PropValue::Str(c.into())).as_ref(),
553                "{class:?}"
554            );
555        }
556    }
557
558    /// protomaps `Places.zoomsIndex`: a city or town with a population starts
559    /// at z7; the `min_zoom` attribute is the zoom range start plus one.
560    #[test]
561    fn overture_city_and_town_with_population_start_at_zoom_7() {
562        for class in ["city", "town"] {
563            let r = process(&make_overture(&[
564                ("subtype", PropValue::Str("locality".into())),
565                ("class", PropValue::Str(class.into())),
566                ("population", PropValue::I64(250_000)),
567            ]))
568            .unwrap();
569            assert_eq!(r.min_zoom, 7, "{class}");
570            assert_eq!(prop(&r, "min_zoom"), Some(&PropValue::I64(8)), "{class}");
571        }
572    }
573
574    /// Mumbai (Q1156) is `Q1156,1,-1,14` in places-wikidata.csv: a locality
575    /// takes min zoom 1 and population rank 14 from the row.
576    #[test]
577    fn overture_locality_in_the_wikidata_table_takes_its_zoom_and_rank() {
578        let r = process(&make_overture(&[
579            ("subtype", PropValue::Str("locality".into())),
580            ("class", PropValue::Str("city".into())),
581            ("population", PropValue::I64(12_442_373)),
582            ("wikidata", PropValue::Str("Q1156".into())),
583        ]))
584        .unwrap();
585        assert_eq!((r.min_zoom, r.max_zoom), (1, 15));
586        assert_eq!(prop(&r, "min_zoom"), Some(&PropValue::I64(2)));
587        assert_eq!(prop(&r, "population_rank"), Some(&PropValue::I64(14)));
588    }
589
590    /// India (Q668) is `Q668,1,6,-1`: a country takes min and max zoom.
591    #[test]
592    fn overture_country_in_the_wikidata_table_takes_its_zoom_range() {
593        let r = process(&make_overture(&[
594            ("subtype", PropValue::Str("country".into())),
595            ("wikidata", PropValue::Str("Q668".into())),
596        ]))
597        .unwrap();
598        assert_eq!((r.min_zoom, r.max_zoom), (1, 6));
599    }
600
601    /// Rows read by eye from places-wikidata.csv (protomaps `cf87de9f`).
602    #[test]
603    fn wikidata_rows_read_as_protomaps_reads_them() {
604        let india = wikidata_zoom("Q668").unwrap();
605        assert_eq!(
606            (india.min_zoom, india.max_zoom, india.rank_max),
607            (1, Some(6), None)
608        );
609        let mumbai = wikidata_zoom("Q1156").unwrap();
610        assert_eq!(
611            (mumbai.min_zoom, mumbai.max_zoom, mumbai.rank_max),
612            (1, None, Some(14))
613        );
614        // Delhi (Q1353) has two rows, `4,9,-1` then `3,-1,14`. The later row
615        // wins, as protomaps' `HashMap.put` does.
616        let delhi = wikidata_zoom("Q1353").unwrap();
617        assert_eq!(
618            (delhi.min_zoom, delhi.max_zoom, delhi.rank_max),
619            (3, None, Some(14))
620        );
621        assert!(wikidata_zoom("Q0").is_none());
622    }
623
624    /// The file has 7,542 data rows; a row that does not parse would be
625    /// dropped without a word.
626    #[test]
627    fn every_wikidata_row_parses() {
628        let rows: Vec<&str> = WIKIDATA_CSV.lines().skip(1).collect();
629        assert_eq!(rows.len(), 7542);
630        for row in rows {
631            assert!(parse_wikidata_row(row).is_some(), "{row}");
632        }
633    }
634
635    #[test]
636    fn overture_hood_subtypes_are_kept() {
637        let cases = [
638            ("macrohood", "macrohood", 11u8),
639            ("neighborhood", "neighbourhood", 12),
640            ("microhood", "neighbourhood", 13),
641            ("dependency", "country", 5),
642        ];
643        for (subtype, kind, zoom) in cases {
644            let r = process(&make_overture(&[(
645                "subtype",
646                PropValue::Str(subtype.into()),
647            )]))
648            .unwrap();
649            assert_eq!(
650                prop(&r, "kind"),
651                Some(&PropValue::Str(kind.into())),
652                "{subtype}"
653            );
654            assert_eq!(r.min_zoom, zoom, "{subtype}");
655        }
656    }
657
658    fn has(r: &ProcessedFeature, key: &str, value: &str) -> bool {
659        r.properties
660            .iter()
661            .any(|(k, v)| k == key && *v == PropValue::Str(value.into()))
662    }
663
664    #[test]
665    fn osm_city_carries_the_names_the_style_reads() {
666        let r = process(&make_osm(&[
667            ("place", "city"),
668            ("name", "کراچی"),
669            ("name:en", "Karachi"),
670            ("name:ur", "کراچی"),
671            ("name:xx", "dropped"),
672        ]))
673        .unwrap();
674        assert!(has(&r, "name", "کراچی"));
675        assert!(has(&r, "script", "Arabic"));
676        assert!(has(&r, "name:en", "Karachi"));
677        assert!(has(&r, "name:ur", "کراچی"));
678        assert!(r.properties.iter().all(|(k, _)| k != "name:xx"));
679    }
680
681    #[test]
682    fn overture_country_carries_name_en_for_the_country_label() {
683        // `get_country_name` reads `name:<lang>` and `name:en` only.
684        let r = process(&make_overture(&[
685            ("subtype", PropValue::Str("country".into())),
686            ("names.primary", PropValue::Str("پاکستان".into())),
687            ("names.common.en", PropValue::Str("Pakistan".into())),
688        ]))
689        .unwrap();
690        assert!(has(&r, "name", "پاکستان"));
691        assert!(has(&r, "script", "Arabic"));
692        assert!(has(&r, "name:en", "Pakistan"));
693    }
694
695    #[test]
696    fn overture_localadmin_is_not_a_place() {
697        // Nor is a missing or an unknown subtype.
698        let localadmin = [("subtype", PropValue::Str("localadmin".into()))];
699        let unknown = [("subtype", PropValue::Str("unknown".into()))];
700        for props in [&localadmin[..], &unknown, &[]] {
701            assert!(process(&make_overture(props)).is_none(), "{props:?}");
702        }
703    }
704
705    #[test]
706    fn population_rank_function() {
707        assert_eq!(population_rank(1_000_000_000), 18);
708        assert_eq!(population_rank(100_000_000), 17);
709        assert_eq!(population_rank(5_000_000), 13);
710        assert_eq!(population_rank(1_000_000), 12);
711        assert_eq!(population_rank(500), 2);
712        assert_eq!(population_rank(200), 2);
713        assert_eq!(population_rank(100), 1);
714        assert_eq!(population_rank(0), 1);
715    }
716
717    #[test]
718    fn osm_country_kind_and_zoom() {
719        let feat = make_osm(&[("place", "country"), ("name", "France")]);
720        let result = process(&feat).unwrap();
721        assert_eq!(result.layer, Layer::Places);
722        // protomaps: zoom range starts at 5, the attribute is 5 + 1.
723        assert_eq!(result.min_zoom, 5);
724        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(6)));
725        assert_eq!(result.max_zoom, 8);
726        assert!(
727            result
728                .properties
729                .iter()
730                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
731        );
732        assert!(
733            result
734                .properties
735                .iter()
736                .any(|(k, v)| k == "kind_detail" && *v == PropValue::Str("country".into()))
737        );
738    }
739
740    #[test]
741    fn osm_city_with_population() {
742        let feat = make_osm(&[
743            ("place", "city"),
744            ("name", "Paris"),
745            ("population", "2161000"),
746        ]);
747        let result = process(&feat).unwrap();
748        assert_eq!(result.min_zoom, 7);
749        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(8)));
750        assert_eq!(result.max_zoom, 15);
751        let pop = result
752            .properties
753            .iter()
754            .find(|(k, _)| k == "population")
755            .map(|(_, v)| v.clone());
756        assert_eq!(pop, Some(PropValue::I64(2_161_000)));
757    }
758
759    #[test]
760    fn osm_city_without_population_gets_default() {
761        let feat = make_osm(&[("place", "city"), ("name", "Smallville")]);
762        let result = process(&feat).unwrap();
763        assert_eq!(result.min_zoom, 8); // no population: city starts at 8
764        let pop = result
765            .properties
766            .iter()
767            .find(|(k, _)| k == "population")
768            .map(|(_, v)| v.clone());
769        assert_eq!(pop, Some(PropValue::I64(5000)));
770    }
771
772    #[test]
773    fn osm_hamlet_default_population() {
774        let feat = make_osm(&[("place", "hamlet"), ("name", "Tiny")]);
775        let result = process(&feat).unwrap();
776        assert_eq!(result.min_zoom, 12); // no population: hamlet starts at 12
777        let pop = result
778            .properties
779            .iter()
780            .find(|(k, _)| k == "population")
781            .map(|(_, v)| v.clone());
782        assert_eq!(pop, Some(PropValue::I64(200)));
783    }
784
785    #[test]
786    fn osm_state_in_us_is_region() {
787        let feat = make_osm(&[
788            ("place", "state"),
789            ("name", "California"),
790            ("ISO3166-1:alpha2", "US"),
791        ]);
792        let result = process(&feat).unwrap();
793        assert!(
794            result
795                .properties
796                .iter()
797                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
798        );
799        assert_eq!(result.min_zoom, 8);
800    }
801
802    #[test]
803    fn osm_state_outside_major_countries_skipped() {
804        let feat = make_osm(&[
805            ("place", "state"),
806            ("name", "Bayern"),
807            ("ISO3166-1:alpha2", "DE"),
808        ]);
809        assert!(process(&feat).is_none());
810    }
811
812    #[test]
813    fn osm_suburb_is_neighbourhood() {
814        let feat = make_osm(&[("place", "suburb"), ("name", "Montmartre")]);
815        let result = process(&feat).unwrap();
816        assert!(
817            result
818                .properties
819                .iter()
820                .any(|(k, v)| k == "kind" && *v == PropValue::Str("neighbourhood".into()))
821        );
822        assert_eq!(result.min_zoom, 11);
823    }
824
825    #[test]
826    fn osm_quarter_is_macrohood() {
827        let feat = make_osm(&[("place", "quarter"), ("name", "Latin Quarter")]);
828        let result = process(&feat).unwrap();
829        assert!(
830            result
831                .properties
832                .iter()
833                .any(|(k, v)| k == "kind" && *v == PropValue::Str("macrohood".into()))
834        );
835        assert_eq!(result.min_zoom, 10);
836    }
837
838    #[test]
839    fn osm_capital_extracted() {
840        let feat = make_osm(&[
841            ("place", "city"),
842            ("name", "Delhi"),
843            ("capital", "yes"),
844            ("population", "11000000"),
845        ]);
846        let result = process(&feat).unwrap();
847        assert!(
848            result
849                .properties
850                .iter()
851                .any(|(k, v)| k == "capital" && *v == PropValue::Str("yes".into()))
852        );
853    }
854
855    #[test]
856    fn osm_wikidata_extracted() {
857        let feat = make_osm(&[
858            ("place", "city"),
859            ("name", "Paris"),
860            ("wikidata", "Q90"),
861            ("population", "2161000"),
862        ]);
863        let result = process(&feat).unwrap();
864        assert!(
865            result
866                .properties
867                .iter()
868                .any(|(k, v)| k == "wikidata" && *v == PropValue::Str("Q90".into()))
869        );
870    }
871
872    /// Mumbai (`Q1156,1,-1,14`) and India (`Q668,1,6,-1`) from OSM.
873    #[test]
874    fn osm_places_in_the_wikidata_table_take_their_zooms() {
875        let city = process(&make_osm(&[
876            ("place", "city"),
877            ("name", "Mumbai"),
878            ("population", "12442373"),
879            ("wikidata", "Q1156"),
880        ]))
881        .unwrap();
882        assert_eq!((city.min_zoom, city.max_zoom), (1, 15));
883        assert_eq!(prop(&city, "min_zoom"), Some(&PropValue::I64(2)));
884        assert_eq!(prop(&city, "population_rank"), Some(&PropValue::I64(14)));
885
886        let country = process(&make_osm(&[
887            ("place", "country"),
888            ("name", "India"),
889            ("wikidata", "Q668"),
890        ]))
891        .unwrap();
892        assert_eq!((country.min_zoom, country.max_zoom), (1, 6));
893    }
894
895    #[test]
896    fn osm_unknown_place_returns_none() {
897        let feat = make_osm(&[("place", "ocean")]);
898        assert!(process(&feat).is_none());
899    }
900
901    #[test]
902    fn osm_non_point_skipped() {
903        let mut properties = HashMap::new();
904        properties.insert("place".to_string(), PropValue::Str("city".to_string()));
905        let feat = InputFeature {
906            id: 1,
907            geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
908                geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]),
909                vec![],
910            ))),
911            properties,
912            bbox: None,
913            source: DataSource::Osm {
914                element_type: OsmElementType::Way,
915                relations: vec![],
916            },
917        };
918        assert!(process(&feat).is_none());
919    }
920
921    #[test]
922    fn osm_population_with_comma() {
923        let feat = make_osm(&[
924            ("place", "city"),
925            ("name", "Bogota"),
926            ("population", "7,181,469"),
927        ]);
928        let result = process(&feat).unwrap();
929        let pop = result
930            .properties
931            .iter()
932            .find(|(k, _)| k == "population")
933            .map(|(_, v)| v.clone());
934        assert_eq!(pop, Some(PropValue::I64(7_181_469)));
935    }
936
937    #[test]
938    fn ne_source_returns_none() {
939        let feat = InputFeature {
940            id: 1,
941            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
942            properties: HashMap::new(),
943            bbox: None,
944            source: DataSource::NaturalEarth {
945                source_layer: "ne_10m_populated_places".to_string(),
946            },
947        };
948        assert!(process(&feat).is_none());
949    }
950}