AfieldTrails / s2-postgis

S2 Cell Id functions for PostgreSQL and PostGIS
MIT License
18 stars 5 forks source link

Suggestion to include a function for cell area #4

Open ppKrauss opened 5 years ago

ppKrauss commented 5 years ago

See also https://github.com/sidewalklabs/s2sphere/issues/38

ppKrauss commented 4 years ago

Solved (!), the functions developed at osm-codes/s2geom-PoC can be used here:

CREATE or replace FUNCTION s2_token_exact_area(token text, ret_meters boolean DEFAULT false) RETURNS float8 AS $f$
  import s2sphere
  kEarthRadiusMeters =  6371010
  steradians = s2sphere.Cell( s2sphere.CellId.from_token(token) ).exact_area()
  return (steradians*kEarthRadiusMeters*kEarthRadiusMeters) if ret_meters else steradians
$f$ LANGUAGE plpython3u IMMUTABLE;
COMMENT ON function s2_cellid_exact_area 
  IS 'Exact area in steradians of a cell-Token, and approximated (better for small cells) in meters';

CREATE or replace FUNCTION s2_cellid_exact_area(id0 bigint, ret_meters boolean DEFAULT false) RETURNS float8
AS $f$
  import s2sphere
  id = s2sphere.CellId(
       int.from_bytes( id0.to_bytes(8,'big',signed=True), 'big', signed=False )
  )
  kEarthRadiusMeters =  6371010
  steradians = s2sphere.Cell( id ).exact_area()
  return (steradians*kEarthRadiusMeters*kEarthRadiusMeters) if ret_meters else steradians
$f$ LANGUAGE plpython3u IMMUTABLE;
COMMENT ON function s2_cellid_exact_area 
  IS 'Exact area in steradians of a cell-ID, and approximated (better for small cells) in meters';

Another important function, to work with any "geo library" (e.g. Turf) or PostGIS, is s2_cellid_geojson() that returns the geometry of the cell in GeoJSON format.