Skip to main content

mln_style/sources/
geojson.rs

1//! GeoJSON sources: features from GeoJSON data that the style or the API
2//! gives, or that the source's URL points to, cut into tiles or clustered.
3//!
4//! The data is tiled and clustered in the world square of the map that
5//! draws the source, Mercator's or a registered projection's; it stays
6//! lng/lat to the app. When the style's projection changes, the map tiles a
7//! source's data again in the new one from its URL's GeoJSON or the
8//! style's. A source keeps no GeoJSON set on it, in any projection.
9
10mod reproject;
11
12use std::sync::{Arc, OnceLock};
13
14use geojson::GeoJson;
15pub use reproject::features_to_world;
16
17use crate::collections::VecMap;
18use crate::conversion::{Convertible, Error as ConversionError};
19use crate::expression::{Expr, Functions};
20use crate::filter::Filter;
21use crate::layer::SourceKind;
22use crate::range::Range;
23use crate::source::{Source, SourceData, SourceTypeInfo, StyleSourceType};
24use crate::{Edit, constants};
25
26/// A `clusterProperties` member: its map expression, then its reduce
27/// expression.
28pub type ClusterExpression = (Arc<Expr>, Arc<Expr>);
29pub type ClusterProperties = VecMap<String, ClusterExpression>;
30
31#[derive(Clone)]
32pub struct GeoJSONOptions {
33    // GeoJSON-VT options
34    pub minzoom: u8,
35    pub maxzoom: u8,
36    pub tile_size: u16,
37    pub buffer: u16,
38    pub tolerance: f64,
39    pub line_metrics: bool,
40
41    // Clustering options
42    pub cluster: bool,
43    pub cluster_radius: u16,
44    pub cluster_max_zoom: u8,
45    pub cluster_min_points: usize,
46    pub cluster_properties: ClusterProperties,
47
48    // Feature ids
49    /// Whether each feature's id is its index in the data, in place of the
50    /// id it has.
51    pub generate_id: bool,
52    /// The property whose value is each feature's id, in place of the id it
53    /// has or [`generate_id`](Self::generate_id) gives it. A feature without
54    /// the property has no id.
55    pub promote_id: Option<String>,
56
57    /// The filter a feature must pass, evaluated at zoom 0, to be tiled or
58    /// clustered, and to take an index under
59    /// [`generate_id`](Self::generate_id).
60    pub filter: Option<Filter>,
61
62    // Update options
63    pub synchronous_update: bool,
64
65    /// The style's attribution for the source, reported by
66    /// `Source::get_attribution`.
67    pub attribution: Option<String>,
68}
69
70impl Default for GeoJSONOptions {
71    fn default() -> Self {
72        GeoJSONOptions {
73            minzoom: 0,
74            maxzoom: 18,
75            tile_size: constants::TILE_SIZE_I,
76            buffer: 128,
77            tolerance: 0.375,
78            line_metrics: false,
79            cluster: false,
80            cluster_radius: 50,
81            cluster_max_zoom: 17,
82            cluster_min_points: 2,
83            cluster_properties: ClusterProperties::new(),
84            generate_id: false,
85            promote_id: None,
86            filter: None,
87            synchronous_update: false,
88            attribution: None,
89        }
90    }
91}
92
93impl std::fmt::Debug for GeoJSONOptions {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        f.debug_struct("GeoJSONOptions")
96            .field("minzoom", &self.minzoom)
97            .field("maxzoom", &self.maxzoom)
98            .field("tile_size", &self.tile_size)
99            .field("buffer", &self.buffer)
100            .field("tolerance", &self.tolerance)
101            .field("line_metrics", &self.line_metrics)
102            .field("cluster", &self.cluster)
103            .field("cluster_radius", &self.cluster_radius)
104            .field("cluster_max_zoom", &self.cluster_max_zoom)
105            .field("cluster_min_points", &self.cluster_min_points)
106            .field("cluster_properties", &self.cluster_properties.keys().collect::<Vec<_>>())
107            .field("generate_id", &self.generate_id)
108            .field("promote_id", &self.promote_id)
109            .field("filter", &self.filter.as_ref().map(Filter::serialize))
110            .field("synchronous_update", &self.synchronous_update)
111            .field("attribution", &self.attribution)
112            .finish()
113    }
114}
115
116impl GeoJSONOptions {
117    /// The default options, as one shared instance.
118    pub fn default_options() -> Arc<GeoJSONOptions> {
119        static OPTIONS: OnceLock<Arc<GeoJSONOptions>> = OnceLock::new();
120        Arc::clone(OPTIONS.get_or_init(|| Arc::new(GeoJSONOptions::default())))
121    }
122}
123
124/// The GeoJSON source type.
125pub struct GeoJsonSourceType;
126
127/// GeoJSON that the style gives as a source's `data`, or why it isn't
128/// GeoJSON, which fails the source as it loads rather than the style.
129pub type InlineGeoJson = Arc<Result<GeoJson, String>>;
130
131/// A GeoJSON source's options.
132#[derive(Clone, Debug)]
133pub struct GeoJsonSourceOptions {
134    pub options: Arc<GeoJSONOptions>,
135    /// The URL of the source's GeoJSON, if it loads it from one.
136    pub url: Option<String>,
137    /// The GeoJSON the style gives, if it gives it rather than a URL.
138    pub inline: Option<InlineGeoJson>,
139    /// `options.synchronous_update` until the source's override replaces it.
140    pub synchronous_update: bool,
141}
142
143impl GeoJsonSourceOptions {
144    #[must_use]
145    pub fn new(options: Arc<GeoJSONOptions>) -> Self {
146        let synchronous_update = options.synchronous_update;
147        GeoJsonSourceOptions { options, url: None, inline: None, synchronous_update }
148    }
149
150    /// Whether the source has GeoJSON to tile again when the style's
151    /// projection changes: a URL to request it from, or the style's.
152    #[must_use]
153    pub fn tiles_again(&self) -> bool {
154        self.url.is_some() || self.inline.is_some()
155    }
156
157    #[must_use]
158    pub fn zoom_range(&self) -> Range<u8> {
159        Range::new(self.options.minzoom, self.options.maxzoom)
160    }
161}
162
163impl StyleSourceType for GeoJsonSourceType {
164    const INFO: SourceTypeInfo = SourceTypeInfo { name: "geojson", layer_kind: SourceKind::Geometry, from_json: true };
165
166    type Options = GeoJsonSourceOptions;
167
168    fn from_json(
169        value: &Convertible<'_>,
170        functions: &Arc<Functions>,
171        error: &mut ConversionError,
172    ) -> Option<SourceData<Self>> {
173        crate::conversion::source::convert_geojson_source(value, functions, error)
174    }
175}
176
177impl GeoJsonSourceType {
178    /// The edit that makes the GeoJSON source `id` load its data from
179    /// `url`. Its data stays until the URL's arrives.
180    pub fn set_url(id: impl Into<String>, url: impl Into<String>) -> Edit {
181        let url = url.into();
182        Edit::update_source::<Self>(id, "a GeoJSON source", |data| {
183            data.options.url = Some(url);
184            data.options.inline = None;
185            data.load += 1;
186            true
187        })
188    }
189
190    /// The edit that sets whether the tiles of the GeoJSON source `id` lay
191    /// out in the call that asks for them, in place of its
192    /// `synchronous_update` option.
193    pub fn set_synchronous(id: impl Into<String>, synchronous: bool) -> Edit {
194        Edit::update_source::<Self>(id, "a GeoJSON source", move |data| {
195            let changed = data.options.synchronous_update != synchronous;
196            data.options.synchronous_update = synchronous;
197            changed
198        })
199    }
200}
201
202/// A GeoJSON source with `options` and no data until it gets some or a URL.
203#[must_use]
204pub fn geojson_source(id: &str, options: Arc<GeoJSONOptions>) -> Source {
205    Source::new(id, SourceData::<GeoJsonSourceType>::new(GeoJsonSourceOptions::new(options)))
206}
207
208#[cfg(test)]
209#[path = "geojson_test.rs"]
210mod tests;