Skip to content

Instantly share code, notes, and snippets.

@wiseman
Created August 4, 2022 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wiseman/c56d61360d9007e5c2c148f177834795 to your computer and use it in GitHub Desktop.
Save wiseman/c56d61360d9007e5c2c148f177834795 to your computer and use it in GitHub Desktop.
Fix trans-antimeridian polygons
/// 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