Skip to content

Instantly share code, notes, and snippets.

@geozelot
Last active February 13, 2023 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geozelot/5cf8425160b98394d0f9ba50ce76917e to your computer and use it in GitHub Desktop.
Save geozelot/5cf8425160b98394d0f9ba50ce76917e to your computer and use it in GitHub Desktop.
PostgreSQL/PostGIS - Close approximation of distance in degrees for a given surface distance in meter at a given location and in a given direction
/*
* Distance in degree to the curve of an ellipse defined by the factor of latitudinal distance at a given
* longitude [x-axis] and 1.0 [y-axis], representing the varying factor by which longitudinal degrees scale
* to latitudinal degrees in relation to surface distance and varying angular direction of measurement.
*
* Returns a very close approximation of distance in degree of a sphere at given @latitude that corresponds to
* @distance meter surface distance, in the direction of north based @azimuth in degree, from the center of the ellipse.
* Angularity defaults to 90.0 (eastward) and shortcuts execution - corresponds to the simple factor of
* reduced surface distance per degree of longitude at increasing latitudes.
*/
CREATE OR REPLACE FUNCTION ST_SurfaceToDegree(
latitude FLOAT,
distance FLOAT,
azimuth FLOAT DEFAULT 90.0
) RETURNS FLOAT IMMUTABLE STRICT PARALLEL SAFE
LANGUAGE 'plpgsql' AS
$BODY$
BEGIN
IF azimuth IN (90.0, 180.0) THEN
RETURN DEGREES(distance / (6371000.0 * COS(RADIANS(latitude))));
END IF;
RETURN SQRT((distance * COS(RADIANS(azimuth - 90))) ^ 2 + (distance / 111194.926 * SIN(RADIANS(azimuth - 90))) ^ 2);
END;
$BODY$
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment