Skip to content

Instantly share code, notes, and snippets.

@andrewxhill
Last active October 13, 2015 20:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewxhill/8795878 to your computer and use it in GitHub Desktop.
Save andrewxhill/8795878 to your computer and use it in GitHub Desktop.
PLPGSQL Function to cross the dateline
--
-- Create a valid GEOMETRY in 3857 like the_geom_webmercator
--
-- @param pointa is GEOMETRY in 3857 like the_geom_webmercator
--
-- @param pointb is GEOMETRY in 3857 like the_geom_webmercator
--
--
CREATE OR REPLACE FUNCTION AXH_CrossDateLine (pointa GEOMETRY, pointb GEOMETRY) RETURNS geometry as $$
DECLARE
westmost GEOMETRY;
eastmost GEOMETRY;
h FLOAT8;
p FLOAT8;
zy FLOAT8;
BEGIN
IF ST_SRID(pointa) != 3857 THEN
pointa = ST_Transform(pointa, 3857);
END IF;
IF ST_SRID(pointb) != 3857 THEN
pointb = ST_Transform(pointb, 3857);
END IF;
IF ST_X(pointa) < ST_X(pointb) THEN
westmost := pointa;
eastmost := pointb;
ELSE
westmost := pointb;
eastmost := pointa;
END IF;
h := GREATEST(ST_Y(eastmost), ST_Y(westmost)) - LEAST(ST_Y(eastmost), ST_Y(westmost));
p := (h / (20037508.34 - ST_X(eastmost) + ST_X(westmost) + 20037508.34 )) * (20037508.34 - ST_X(eastmost));
zy := LEAST(ST_Y(eastmost), ST_Y(westmost)) + p;
RETURN ST_Collect(
ST_MakeLine(eastmost, ST_SetSRID(ST_MakePoint(20037508.34, zy),3857)),
ST_MakeLine(ST_SetSRID(ST_MakePoint(-20037508.34, zy),3857), westmost)
);
END;
$$ language plpgsql IMMUTABLE;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment