Fix trans-antimeridian polygons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Fix geojson polygons that span the antimeridian and have arcs > 180 | |
/// degrees. This is a workaround for a bug in the underlying H3 library: | |
/// <https://github.com/uber/h3/issues/561> | |
/// | |
/// This code is based on nrabinowitz's code in | |
/// <https://observablehq.com/@nrabinowitz/mapbox-utils> | |
pub fn fix_trans_meridian_coordinate(coord: &mut geo_types::Coordinate<f64>) { | |
if coord.x < 0.0 { | |
coord.x += 360.0; | |
} | |
} | |
pub fn fix_trans_meridian_linestring(line: &mut geo_types::LineString<f64>) -> bool { | |
let is_transmeridian = { | |
if line | |
.coords() | |
.tuple_windows() | |
.any(|(a, b)| (a.x - b.x).abs() > 180.0) | |
{ | |
true | |
} else { | |
let first = line.coords().next().unwrap(); | |
let last = line.coords().last().unwrap(); | |
(first.x - last.x).abs() > 180.0 | |
} | |
}; | |
if is_transmeridian { | |
line.coords_mut().for_each(fix_trans_meridian_coordinate); | |
true | |
} else { | |
false | |
} | |
} | |
pub fn fix_trans_meridian(poly: &mut geo_types::Polygon<f64>) -> bool { | |
let mut fixed = false; | |
poly.exterior_mut(|l| fixed = fix_trans_meridian_linestring(l)); | |
fixed | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment