Skip to main content

crisol_plot/
geo.rs

1//! GeoJSON features as plot series.
2
3use std::sync::Arc;
4
5use crisol_geo::{GeoJson, Projection};
6use crisol_plot_core::transform::YAxis;
7
8use crate::plot::Series;
9
10/// Convert a GeoJSON layer to line and scatter series in plot coordinates.
11pub fn series(layer: &GeoJson, projection: Projection) -> Vec<Series<'static>> {
12    let mut out = Vec::new();
13    for (name, paths) in layer.project(projection) {
14        let label = name.unwrap_or_else(|| "geo".to_owned());
15        for (index, path) in paths.into_iter().enumerate() {
16            if path.len() == 1 {
17                let mut points = Vec::with_capacity(path.len());
18                points.extend(path);
19                out.push(Series::scatter(format!("{label} {index}"), points));
20            } else if path.len() >= 2 {
21                out.push(Series::line(format!("{label} {index}"), path));
22            }
23        }
24    }
25    out
26}
27
28/// A tile URL and the layers that cover it, for map overlays.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct TileRequest {
31    /// URL template with `{z}`, `{x}`, and `{y}`.
32    pub template: String,
33}
34
35impl TileRequest {
36    /// A template request.
37    pub fn new(template: impl Into<String>) -> Self {
38        Self {
39            template: template.into(),
40        }
41    }
42
43    /// The URL for `tile`.
44    pub fn url(&self, grid: crisol_geo::TileGrid, tile: crisol_geo::Tile) -> String {
45        grid.url(&self.template, tile)
46    }
47}
48
49/// A convenience type for applications that keep one projection and one tile template.
50#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct GeoLayer {
52    /// Projection for the GeoJSON.
53    pub projection: Projection,
54    /// Tile request template.
55    pub tiles: Option<TileRequest>,
56}
57
58impl Default for GeoLayer {
59    fn default() -> Self {
60        Self {
61            projection: Projection::WebMercator,
62            tiles: None,
63        }
64    }
65}
66
67/// Apply a layer to an existing plot.
68pub fn add_to(plot: crate::plot::Plot<'static>, layer: &GeoJson, style: &GeoLayer) -> crate::plot::Plot<'static> {
69    let mut plot = plot;
70    for series in series(layer, style.projection) {
71        plot = plot.series(series);
72    }
73    plot
74}
75
76/// The y axis used by geographic series (the left axis).
77pub const GEO_AXIS: YAxis = YAxis::Left;
78
79/// Keep the Arc import used by applications that share a layer between windows.
80pub fn shared(layer: GeoJson) -> Arc<GeoJson> {
81    Arc::new(layer)
82}