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 crate::layers::Layer;
11use crate::source::input::{DataSource, InputFeature};
12use crate::tile::feature::PropValue;
13
14use super::buildings::ProcessedFeature;
15
16/// Zoom overrides per Wikidata id: protomaps basemaps `places.csv` at
17/// commit `cf87de9f`, unchanged (BSD-3-Clause, see
18/// `places-wikidata.LICENSE`). Columns: `wikidata,minzoom,maxzoom,rankmax`;
19/// `-1` means not set. It is what puts countries and large cities on the map
20/// from z1–z6, as in protomaps `Places.getZoomsPops`.
21const WIKIDATA_CSV: &str = include_str!("places-wikidata.csv");
22
23/// One row of [`WIKIDATA_CSV`].
24#[derive(Debug, Clone, Copy)]
25struct WikidataZoom {
26    /// Zoom range start.
27    min_zoom: u8,
28    /// Zoom range end, for countries and regions.
29    max_zoom: Option<u8>,
30    /// Population rank, for localities.
31    rank_max: Option<u8>,
32}
33
34/// Parse one `wikidata,minzoom,maxzoom,rankmax` row.
35fn parse_wikidata_row(row: &str) -> Option<(&str, WikidataZoom)> {
36    let mut columns = row.split(',');
37    let id = columns.next()?;
38    let mut number = || columns.next()?.trim().parse::<i16>().ok();
39    let (min_zoom, max_zoom, rank_max) = (number()?, number()?, number()?);
40    Some((
41        id,
42        WikidataZoom {
43            min_zoom: u8::try_from(min_zoom).ok()?,
44            max_zoom: u8::try_from(max_zoom).ok(),
45            rank_max: u8::try_from(rank_max).ok(),
46        },
47    ))
48}
49
50/// The row for a Wikidata id. A later row for the same id wins, as in
51/// protomaps (`HashMap.put`).
52fn wikidata_zoom(id: &str) -> Option<WikidataZoom> {
53    static TABLE: OnceLock<HashMap<&'static str, WikidataZoom>> = OnceLock::new();
54    TABLE
55        .get_or_init(|| {
56            WIKIDATA_CSV
57                .lines()
58                .skip(1)
59                .filter_map(parse_wikidata_row)
60                .collect()
61        })
62        .get(id)
63        .copied()
64}
65
66/// Zoom range and population rank after the Wikidata override.
67struct Zooms {
68    min_zoom: u8,
69    max_zoom: u8,
70    population_rank: Option<u8>,
71}
72
73/// Apply the [`WIKIDATA_CSV`] row, as protomaps `Places.getZoomsPops`:
74/// countries and regions take its zoom range, localities its min zoom and
75/// population rank.
76fn apply_wikidata(kind: &str, wikidata: Option<&str>, zooms: Zooms) -> Zooms {
77    let Some(row) = wikidata.and_then(wikidata_zoom) else {
78        return zooms;
79    };
80    match kind {
81        "country" | "region" => Zooms {
82            min_zoom: row.min_zoom,
83            max_zoom: row.max_zoom.unwrap_or(zooms.max_zoom),
84            ..zooms
85        },
86        "locality" => Zooms {
87            min_zoom: row.min_zoom,
88            population_rank: row.rank_max.or(zooms.population_rank),
89            ..zooms
90        },
91        _ => zooms,
92    }
93}
94
95/// Population break points for rank calculation.
96///
97/// Rank is determined by finding the first threshold the population meets
98/// or exceeds. Higher rank = more prominent place.
99const POP_BREAKS: &[u64] = &[
100    1_000_000_000,
101    100_000_000,
102    50_000_000,
103    20_000_000,
104    10_000_000,
105    5_000_000,
106    1_000_000,
107    500_000,
108    200_000,
109    100_000,
110    50_000,
111    20_000,
112    10_000,
113    5_000,
114    2_000,
115    1_000,
116    200,
117    0,
118];
119
120/// Countries where state/province gets region classification.
121const REGION_COUNTRIES: &[&str] = &["US", "CA", "BR", "IN", "CN", "AU"];
122
123/// Calculate population rank from an absolute population value.
124///
125/// Returns a rank from 0 (smallest) to 18 (largest, >= 1 billion).
126fn population_rank(population: u64) -> u8 {
127    for (i, &threshold) in POP_BREAKS.iter().enumerate() {
128        if population >= threshold {
129            return (POP_BREAKS.len() - i) as u8;
130        }
131    }
132    0
133}
134
135/// Process a feature into a places layer feature.
136///
137/// Routes to the appropriate handler based on data source.
138pub fn process(feature: &InputFeature) -> Option<ProcessedFeature> {
139    match &feature.source {
140        DataSource::Overture { .. } => process_overture(feature),
141        DataSource::Osm { .. } => process_osm(feature),
142        _ => None,
143    }
144}
145
146/// Process an Overture divisions/division feature.
147///
148/// Localities take their zoom from `class`: cities and towns at z7 as in
149/// protomaps `Places.zoomsIndex` (z8 and z9 without a population), villages
150/// at z12, hamlets at z13, others at z10. A flat z10 put all 3.25M villages
151/// and hamlets in the release on screen at z10. `macrohood` and `microhood`
152/// map to the protomaps `macrohood` and `neighbourhood` kinds, as in
153/// protomaps `Places.processOverture`. A row in [`WIKIDATA_CSV`] overrides
154/// the zoom; the `min_zoom` attribute is the range start plus one, as in
155/// protomaps.
156fn process_overture(feature: &InputFeature) -> Option<ProcessedFeature> {
157    let subtype = feature.get_str("subtype")?;
158    let class = feature.get_str("class");
159    let population = feature.get_i64("population");
160    let has_population = population.is_some_and(|p| p > 0);
161
162    let (kind, min_zoom) = match subtype {
163        "country" | "dependency" => ("country", 5u8),
164        "region" => ("region", 8),
165        "county" => ("county", 7),
166        "locality" => match class {
167            Some("city") => ("locality", if has_population { 7 } else { 8 }),
168            Some("town") => ("locality", if has_population { 7 } else { 9 }),
169            Some("village") => ("locality", 12),
170            Some("hamlet") => ("locality", 13),
171            _ => ("locality", 10),
172        },
173        "macrohood" => ("macrohood", 11),
174        "neighbourhood" | "neighborhood" => ("neighbourhood", 12),
175        "microhood" => ("neighbourhood", 13),
176        _ => return None,
177    };
178
179    let zooms = apply_wikidata(
180        kind,
181        feature.get_str("wikidata"),
182        Zooms {
183            min_zoom,
184            max_zoom: 15,
185            population_rank: population.map(|p| population_rank(p.max(0) as u64)),
186        },
187    );
188
189    let mut properties = Vec::with_capacity(7);
190    properties.push(("kind".into(), PropValue::Str(kind.into())));
191    if let Some(class) = class {
192        properties.push(("kind_detail".into(), PropValue::Str(class.to_string())));
193    }
194
195    if let Some(pop) = population {
196        properties.push(("population".into(), PropValue::I64(pop)));
197    }
198    if let Some(rank) = zooms.population_rank {
199        properties.push(("population_rank".into(), PropValue::I64(i64::from(rank))));
200    }
201
202    if let Some(name) = feature.get_str("names.primary").or(feature.get_str("name")) {
203        properties.push(("name".into(), PropValue::Str(name.to_string())));
204    }
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    if let Some(name) = feature.get_str("name") {
426        properties.push(("name".into(), PropValue::Str(name.to_string())));
427    }
428
429    properties.push((
430        "min_zoom".into(),
431        PropValue::I64(i64::from(zooms.min_zoom) + 1),
432    ));
433
434    Some(ProcessedFeature {
435        id: feature.id,
436        geometry: feature.geometry.clone(),
437        layer: Layer::Places,
438        min_zoom: zooms.min_zoom,
439        max_zoom: zooms.max_zoom,
440        sort_rank,
441        properties,
442    })
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448    use crate::source::input::{DataSource, OsmElementType};
449    use std::collections::HashMap;
450    use std::sync::Arc;
451
452    fn make_overture(props: &[(&str, PropValue)]) -> InputFeature {
453        let mut properties = HashMap::new();
454        for (k, v) in props {
455            properties.insert(k.to_string(), v.clone());
456        }
457        InputFeature {
458            id: 1,
459            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(2.35, 48.86))),
460            properties,
461            bbox: None,
462            source: DataSource::Overture {
463                theme: String::new(),
464                otype: String::new(),
465            },
466        }
467    }
468
469    fn make_osm(tags: &[(&str, &str)]) -> InputFeature {
470        let mut properties = HashMap::new();
471        for (k, v) in tags {
472            properties.insert(k.to_string(), PropValue::Str(v.to_string()));
473        }
474        InputFeature {
475            id: 42,
476            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(2.35, 48.86))),
477            properties,
478            bbox: None,
479            source: DataSource::Osm {
480                element_type: OsmElementType::Node,
481                relations: vec![],
482            },
483        }
484    }
485
486    #[test]
487    fn overture_country_has_correct_kind_and_zoom() {
488        let feat = make_overture(&[("subtype", PropValue::Str("country".into()))]);
489        let result = process(&feat).unwrap();
490        assert_eq!(result.layer, Layer::Places);
491        assert_eq!(result.min_zoom, 5);
492        assert_eq!(result.sort_rank, 300);
493        assert!(
494            result
495                .properties
496                .iter()
497                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
498        );
499    }
500
501    #[test]
502    fn overture_locality_without_class_starts_at_zoom_10() {
503        let feat = make_overture(&[("subtype", PropValue::Str("locality".into()))]);
504        let result = process(&feat).unwrap();
505        assert_eq!(result.min_zoom, 10);
506        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(11)));
507    }
508
509    #[test]
510    fn overture_population_rank_calculated() {
511        let feat = make_overture(&[
512            ("subtype", PropValue::Str("locality".into())),
513            ("population", PropValue::I64(5_000_000)),
514        ]);
515        let result = process(&feat).unwrap();
516        let rank = result
517            .properties
518            .iter()
519            .find(|(k, _)| k == "population_rank")
520            .map(|(_, v)| v.clone());
521        assert_eq!(rank, Some(PropValue::I64(13)));
522    }
523
524    fn prop<'a>(r: &'a ProcessedFeature, key: &str) -> Option<&'a PropValue> {
525        r.properties.iter().find(|(k, _)| k == key).map(|(_, v)| v)
526    }
527
528    /// (subtype, class) pairs from the 2026-08-19.0 release. Cities and towns
529    /// without a population follow protomaps `Places.zoomsIndex`: city 8,
530    /// town 9 (`pm:populationFallback`).
531    #[test]
532    fn overture_locality_zoom_follows_class() {
533        let cases = [
534            (Some("city"), 8u8),
535            (Some("town"), 9),
536            (None, 10),
537            (Some("village"), 12),
538            (Some("hamlet"), 13),
539        ];
540        for (class, zoom) in cases {
541            let mut props = vec![("subtype", PropValue::Str("locality".into()))];
542            if let Some(c) = class {
543                props.push(("class", PropValue::Str(c.into())));
544            }
545            let r = process(&make_overture(&props)).unwrap();
546            assert_eq!(
547                prop(&r, "kind"),
548                Some(&PropValue::Str("locality".into())),
549                "{class:?}"
550            );
551            assert_eq!(r.min_zoom, zoom, "{class:?}");
552            assert_eq!(
553                prop(&r, "kind_detail"),
554                class.map(|c| PropValue::Str(c.into())).as_ref(),
555                "{class:?}"
556            );
557        }
558    }
559
560    /// protomaps `Places.zoomsIndex`: a city or town with a population starts
561    /// at z7; the `min_zoom` attribute is the zoom range start plus one.
562    #[test]
563    fn overture_city_and_town_with_population_start_at_zoom_7() {
564        for class in ["city", "town"] {
565            let r = process(&make_overture(&[
566                ("subtype", PropValue::Str("locality".into())),
567                ("class", PropValue::Str(class.into())),
568                ("population", PropValue::I64(250_000)),
569            ]))
570            .unwrap();
571            assert_eq!(r.min_zoom, 7, "{class}");
572            assert_eq!(prop(&r, "min_zoom"), Some(&PropValue::I64(8)), "{class}");
573        }
574    }
575
576    /// Mumbai (Q1156) is `Q1156,1,-1,14` in places-wikidata.csv: a locality
577    /// takes min zoom 1 and population rank 14 from the row.
578    #[test]
579    fn overture_locality_in_the_wikidata_table_takes_its_zoom_and_rank() {
580        let r = process(&make_overture(&[
581            ("subtype", PropValue::Str("locality".into())),
582            ("class", PropValue::Str("city".into())),
583            ("population", PropValue::I64(12_442_373)),
584            ("wikidata", PropValue::Str("Q1156".into())),
585        ]))
586        .unwrap();
587        assert_eq!((r.min_zoom, r.max_zoom), (1, 15));
588        assert_eq!(prop(&r, "min_zoom"), Some(&PropValue::I64(2)));
589        assert_eq!(prop(&r, "population_rank"), Some(&PropValue::I64(14)));
590    }
591
592    /// India (Q668) is `Q668,1,6,-1`: a country takes min and max zoom.
593    #[test]
594    fn overture_country_in_the_wikidata_table_takes_its_zoom_range() {
595        let r = process(&make_overture(&[
596            ("subtype", PropValue::Str("country".into())),
597            ("wikidata", PropValue::Str("Q668".into())),
598        ]))
599        .unwrap();
600        assert_eq!((r.min_zoom, r.max_zoom), (1, 6));
601    }
602
603    /// Rows read by eye from places-wikidata.csv (protomaps `cf87de9f`).
604    #[test]
605    fn wikidata_rows_read_as_protomaps_reads_them() {
606        let india = wikidata_zoom("Q668").unwrap();
607        assert_eq!(
608            (india.min_zoom, india.max_zoom, india.rank_max),
609            (1, Some(6), None)
610        );
611        let mumbai = wikidata_zoom("Q1156").unwrap();
612        assert_eq!(
613            (mumbai.min_zoom, mumbai.max_zoom, mumbai.rank_max),
614            (1, None, Some(14))
615        );
616        // Delhi (Q1353) has two rows, `4,9,-1` then `3,-1,14`. The later row
617        // wins, as protomaps' `HashMap.put` does.
618        let delhi = wikidata_zoom("Q1353").unwrap();
619        assert_eq!(
620            (delhi.min_zoom, delhi.max_zoom, delhi.rank_max),
621            (3, None, Some(14))
622        );
623        assert!(wikidata_zoom("Q0").is_none());
624    }
625
626    /// The file has 7,542 data rows; a row that does not parse would be
627    /// dropped without a word.
628    #[test]
629    fn every_wikidata_row_parses() {
630        let rows: Vec<&str> = WIKIDATA_CSV.lines().skip(1).collect();
631        assert_eq!(rows.len(), 7542);
632        for row in rows {
633            assert!(parse_wikidata_row(row).is_some(), "{row}");
634        }
635    }
636
637    #[test]
638    fn overture_hood_subtypes_are_kept() {
639        let cases = [
640            ("macrohood", "macrohood", 11u8),
641            ("neighborhood", "neighbourhood", 12),
642            ("microhood", "neighbourhood", 13),
643            ("dependency", "country", 5),
644        ];
645        for (subtype, kind, zoom) in cases {
646            let r = process(&make_overture(&[(
647                "subtype",
648                PropValue::Str(subtype.into()),
649            )]))
650            .unwrap();
651            assert_eq!(
652                prop(&r, "kind"),
653                Some(&PropValue::Str(kind.into())),
654                "{subtype}"
655            );
656            assert_eq!(r.min_zoom, zoom, "{subtype}");
657        }
658    }
659
660    #[test]
661    fn overture_localadmin_is_not_a_place() {
662        // Nor is a missing or an unknown subtype.
663        let localadmin = [("subtype", PropValue::Str("localadmin".into()))];
664        let unknown = [("subtype", PropValue::Str("unknown".into()))];
665        for props in [&localadmin[..], &unknown, &[]] {
666            assert!(process(&make_overture(props)).is_none(), "{props:?}");
667        }
668    }
669
670    #[test]
671    fn population_rank_function() {
672        assert_eq!(population_rank(1_000_000_000), 18);
673        assert_eq!(population_rank(100_000_000), 17);
674        assert_eq!(population_rank(5_000_000), 13);
675        assert_eq!(population_rank(1_000_000), 12);
676        assert_eq!(population_rank(500), 2);
677        assert_eq!(population_rank(200), 2);
678        assert_eq!(population_rank(100), 1);
679        assert_eq!(population_rank(0), 1);
680    }
681
682    #[test]
683    fn osm_country_kind_and_zoom() {
684        let feat = make_osm(&[("place", "country"), ("name", "France")]);
685        let result = process(&feat).unwrap();
686        assert_eq!(result.layer, Layer::Places);
687        // protomaps: zoom range starts at 5, the attribute is 5 + 1.
688        assert_eq!(result.min_zoom, 5);
689        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(6)));
690        assert_eq!(result.max_zoom, 8);
691        assert!(
692            result
693                .properties
694                .iter()
695                .any(|(k, v)| k == "kind" && *v == PropValue::Str("country".into()))
696        );
697        assert!(
698            result
699                .properties
700                .iter()
701                .any(|(k, v)| k == "kind_detail" && *v == PropValue::Str("country".into()))
702        );
703    }
704
705    #[test]
706    fn osm_city_with_population() {
707        let feat = make_osm(&[
708            ("place", "city"),
709            ("name", "Paris"),
710            ("population", "2161000"),
711        ]);
712        let result = process(&feat).unwrap();
713        assert_eq!(result.min_zoom, 7);
714        assert_eq!(prop(&result, "min_zoom"), Some(&PropValue::I64(8)));
715        assert_eq!(result.max_zoom, 15);
716        let pop = result
717            .properties
718            .iter()
719            .find(|(k, _)| k == "population")
720            .map(|(_, v)| v.clone());
721        assert_eq!(pop, Some(PropValue::I64(2_161_000)));
722    }
723
724    #[test]
725    fn osm_city_without_population_gets_default() {
726        let feat = make_osm(&[("place", "city"), ("name", "Smallville")]);
727        let result = process(&feat).unwrap();
728        assert_eq!(result.min_zoom, 8); // no population: city starts at 8
729        let pop = result
730            .properties
731            .iter()
732            .find(|(k, _)| k == "population")
733            .map(|(_, v)| v.clone());
734        assert_eq!(pop, Some(PropValue::I64(5000)));
735    }
736
737    #[test]
738    fn osm_hamlet_default_population() {
739        let feat = make_osm(&[("place", "hamlet"), ("name", "Tiny")]);
740        let result = process(&feat).unwrap();
741        assert_eq!(result.min_zoom, 12); // no population: hamlet starts at 12
742        let pop = result
743            .properties
744            .iter()
745            .find(|(k, _)| k == "population")
746            .map(|(_, v)| v.clone());
747        assert_eq!(pop, Some(PropValue::I64(200)));
748    }
749
750    #[test]
751    fn osm_state_in_us_is_region() {
752        let feat = make_osm(&[
753            ("place", "state"),
754            ("name", "California"),
755            ("ISO3166-1:alpha2", "US"),
756        ]);
757        let result = process(&feat).unwrap();
758        assert!(
759            result
760                .properties
761                .iter()
762                .any(|(k, v)| k == "kind" && *v == PropValue::Str("region".into()))
763        );
764        assert_eq!(result.min_zoom, 8);
765    }
766
767    #[test]
768    fn osm_state_outside_major_countries_skipped() {
769        let feat = make_osm(&[
770            ("place", "state"),
771            ("name", "Bayern"),
772            ("ISO3166-1:alpha2", "DE"),
773        ]);
774        assert!(process(&feat).is_none());
775    }
776
777    #[test]
778    fn osm_suburb_is_neighbourhood() {
779        let feat = make_osm(&[("place", "suburb"), ("name", "Montmartre")]);
780        let result = process(&feat).unwrap();
781        assert!(
782            result
783                .properties
784                .iter()
785                .any(|(k, v)| k == "kind" && *v == PropValue::Str("neighbourhood".into()))
786        );
787        assert_eq!(result.min_zoom, 11);
788    }
789
790    #[test]
791    fn osm_quarter_is_macrohood() {
792        let feat = make_osm(&[("place", "quarter"), ("name", "Latin Quarter")]);
793        let result = process(&feat).unwrap();
794        assert!(
795            result
796                .properties
797                .iter()
798                .any(|(k, v)| k == "kind" && *v == PropValue::Str("macrohood".into()))
799        );
800        assert_eq!(result.min_zoom, 10);
801    }
802
803    #[test]
804    fn osm_capital_extracted() {
805        let feat = make_osm(&[
806            ("place", "city"),
807            ("name", "Delhi"),
808            ("capital", "yes"),
809            ("population", "11000000"),
810        ]);
811        let result = process(&feat).unwrap();
812        assert!(
813            result
814                .properties
815                .iter()
816                .any(|(k, v)| k == "capital" && *v == PropValue::Str("yes".into()))
817        );
818    }
819
820    #[test]
821    fn osm_wikidata_extracted() {
822        let feat = make_osm(&[
823            ("place", "city"),
824            ("name", "Paris"),
825            ("wikidata", "Q90"),
826            ("population", "2161000"),
827        ]);
828        let result = process(&feat).unwrap();
829        assert!(
830            result
831                .properties
832                .iter()
833                .any(|(k, v)| k == "wikidata" && *v == PropValue::Str("Q90".into()))
834        );
835    }
836
837    /// Mumbai (`Q1156,1,-1,14`) and India (`Q668,1,6,-1`) from OSM.
838    #[test]
839    fn osm_places_in_the_wikidata_table_take_their_zooms() {
840        let city = process(&make_osm(&[
841            ("place", "city"),
842            ("name", "Mumbai"),
843            ("population", "12442373"),
844            ("wikidata", "Q1156"),
845        ]))
846        .unwrap();
847        assert_eq!((city.min_zoom, city.max_zoom), (1, 15));
848        assert_eq!(prop(&city, "min_zoom"), Some(&PropValue::I64(2)));
849        assert_eq!(prop(&city, "population_rank"), Some(&PropValue::I64(14)));
850
851        let country = process(&make_osm(&[
852            ("place", "country"),
853            ("name", "India"),
854            ("wikidata", "Q668"),
855        ]))
856        .unwrap();
857        assert_eq!((country.min_zoom, country.max_zoom), (1, 6));
858    }
859
860    #[test]
861    fn osm_unknown_place_returns_none() {
862        let feat = make_osm(&[("place", "ocean")]);
863        assert!(process(&feat).is_none());
864    }
865
866    #[test]
867    fn osm_non_point_skipped() {
868        let mut properties = HashMap::new();
869        properties.insert("place".to_string(), PropValue::Str("city".to_string()));
870        let feat = InputFeature {
871            id: 1,
872            geometry: Arc::new(geo::Geometry::Polygon(geo::Polygon::new(
873                geo::LineString::from(vec![(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 0.0)]),
874                vec![],
875            ))),
876            properties,
877            bbox: None,
878            source: DataSource::Osm {
879                element_type: OsmElementType::Way,
880                relations: vec![],
881            },
882        };
883        assert!(process(&feat).is_none());
884    }
885
886    #[test]
887    fn osm_population_with_comma() {
888        let feat = make_osm(&[
889            ("place", "city"),
890            ("name", "Bogota"),
891            ("population", "7,181,469"),
892        ]);
893        let result = process(&feat).unwrap();
894        let pop = result
895            .properties
896            .iter()
897            .find(|(k, _)| k == "population")
898            .map(|(_, v)| v.clone());
899        assert_eq!(pop, Some(PropValue::I64(7_181_469)));
900    }
901
902    #[test]
903    fn ne_source_returns_none() {
904        let feat = InputFeature {
905            id: 1,
906            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(0.0, 0.0))),
907            properties: HashMap::new(),
908            bbox: None,
909            source: DataSource::NaturalEarth {
910                source_layer: "ne_10m_populated_places".to_string(),
911            },
912        };
913        assert!(process(&feat).is_none());
914    }
915}