Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / dem_ingest / src / tilemath.rs
tilemath.rs38 lines · 1.2 KiBRaw
| 1 | //! Slippy / web-mercator tile math shared by the bbox walk and the sampler. |
| 2 | |
| 3 | use std::f64::consts::PI; |
| 4 | |
| 5 | pub fn lon_to_tile_x(lon: f64, z: u8) -> f64 { |
| 6 | (lon + 180.0) / 360.0 * (1u64 << z) as f64 |
| 7 | } |
| 8 | |
| 9 | pub fn lat_to_tile_y(lat: f64, z: u8) -> f64 { |
| 10 | let r = lat.clamp(-85.05112878, 85.05112878).to_radians(); |
| 11 | (1.0 - (r.tan() + 1.0 / r.cos()).ln() / PI) / 2.0 * (1u64 << z) as f64 |
| 12 | } |
| 13 | |
| 14 | pub fn tile_x_to_lon(x: f64, z: u8) -> f64 { |
| 15 | x / (1u64 << z) as f64 * 360.0 - 180.0 |
| 16 | } |
| 17 | |
| 18 | pub fn tile_y_to_lat(y: f64, z: u8) -> f64 { |
| 19 | let n = PI * (1.0 - 2.0 * y / (1u64 << z) as f64); |
| 20 | n.sinh().atan().to_degrees() |
| 21 | } |
| 22 | |
| 23 | #[cfg(test)] |
| 24 | mod tests { |
| 25 | use super::*; |
| 26 | |
| 27 | #[test] |
| 28 | fn the_slippy_math_round_trips_a_tile_corner() { |
| 29 | // A tile's top-left corner maps to a lon/lat that maps back to the tile origin. |
| 30 | for z in [0u8, 8, 12, 14] { |
| 31 | let (x, y) = (5u64.min((1 << z) - 1), 9u64.min((1 << z) - 1)); |
| 32 | let lon = tile_x_to_lon(x as f64, z); |
| 33 | let lat = tile_y_to_lat(y as f64, z); |
| 34 | assert!((lon_to_tile_x(lon, z) - x as f64).abs() < 1e-6, "z{z} lon round trip"); |
| 35 | assert!((lat_to_tile_y(lat, z) - y as f64).abs() < 1e-6, "z{z} lat round trip"); |
| 36 | } |
| 37 | } |
| 38 | } |