-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsicob_transformtowebmercator.sql
More file actions
75 lines (67 loc) · 2.38 KB
/
Copy pathsicob_transformtowebmercator.sql
File metadata and controls
75 lines (67 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
SET CLIENT_ENCODING TO 'utf8';
CREATE OR REPLACE FUNCTION public.sicob_transformtowebmercator(geom geometry)
RETURNS geometry
LANGUAGE plpgsql
IMMUTABLE STRICT
AS $function$
DECLARE
valid_extent GEOMETRY;
latlon_input GEOMETRY;
clipped_input GEOMETRY;
to_webmercator GEOMETRY;
ret GEOMETRY;
BEGIN
--REPROYECTA UNA GEOMETRIA AL SISTEMA WEBMERCATOR PARA APLICACIONES DE WEBMAPPING
---------------------------------------------------------------------------------
IF ST_Srid(geom) = 3857 THEN
RETURN geom;
END IF;
-- This is the valid web mercator extent
--
-- NOTE: some sources set the valid latitude range
-- to -85.0511 to 85.0511 but as long as proj
-- does not complain we are happy
--
valid_extent := ST_MakeEnvelope(-180, -89, 180, 89, 4326);
-- Then we transform to WGS84 latlon, which is
-- where we have known coordinates for the clipping
--
latlon_input := ST_Transform(geom, 4326);
-- Don't bother clipping if the geometry boundary doesn't
-- go outside the valid extent.
IF latlon_input @ valid_extent THEN
RETURN ST_Transform(latlon_input, 3857);
END IF;
-- Since we're going to use ST_Intersection on input
-- we'd better ensure the input is valid
-- TODO: only do this if the first ST_Intersection fails ?
IF ST_Dimension(geom) != 0 AND
-- See http://trac.osgeo.org/postgis/ticket/1719
GeometryType(geom) != 'GEOMETRYCOLLECTION'
THEN
BEGIN
latlon_input := ST_MakeValid(latlon_input);
EXCEPTION
WHEN OTHERS THEN
-- See http://github.com/Vizzuality/cartodb/issues/931
RAISE WARNING 'Could not clean input geometry: %', SQLERRM;
RETURN NULL;
END;
latlon_input := ST_CollectionExtract(latlon_input, ST_Dimension(geom)+1);
END IF;
-- Then we clip, trying to retain the input type
-- TODO: catch exceptions here too ?
clipped_input := ST_Intersection(latlon_input, valid_extent);
-- We transform to web mercator
to_webmercator := ST_Transform(clipped_input, 3857);
-- Finally we convert EMPTY to NULL
-- See https://github.com/Vizzuality/cartodb/issues/706
-- And retain "multi" status
ret := CASE WHEN ST_IsEmpty(to_webmercator) THEN NULL::geometry
WHEN GeometryType(geom) LIKE 'MULTI%' THEN ST_Multi(to_webmercator)
ELSE to_webmercator
END;
RETURN ret;
END
$function$