熟悉GIS开发的小伙伴,都知道Polygon和MultiPolygon是可以有洞的,MultiPolygon内的Polygon有可能是不相邻的。在做一些三方方平台对接时,可能出现不支持带洞的Polygon或者MultiPolygon。今天这里分享一下,如何基于PostGIS实现
- 如何去除Polygon和MultiPolygon图形内的洞
- 如何将MultiPolygon保留轮廓转为Polygon
去除洞
使用下面代码,可以去除Polygon内的洞
select ST_BuildArea(st_exteriorring(geom))
- 去除前
- 去除后
去除Polygon和MultiPolygon图形内的洞 脚本
CREATE OR REPLACE FUNCTION "public"."polygon_remove_hole"("m_polygon" geometry)
RETURNS geometry AS
$BODY$
DECLARE
--去除多边形内的洞
polygon_type text;
temp _geometry;
temp_polygon geometry;
BEGIN
polygon_type := GeometryType(m_polygon);
raise notice '类型-%', polygon_type;
--简单
if polygon_type = 'MULTIPOLYGON' then
raise notice '类型-%', polygon_type;
temp := array []::_geometry;
for temp_polygon in (select geom from ST_Dump(m_polygon))
loop
if ST_NumInteriorRings(temp_polygon) > 0 then
raise notice '类型-有洞%',GeometryType(temp_polygon);
temp := array_append(temp, ST_BuildArea(ST_ExteriorRing(temp_polygon)));
else
raise notice '类型-无洞';
temp := array_append(temp, temp_polygon);
end if;
end loop;
return ST_Union(temp);
ELSEIF polygon_type = 'GEOMETRYCOLLECTION' then
raise notice '类型-%', polygon_type;
temp := array []::_geometry;
for temp_polygon in (select geom from ST_Dump(m_polygon))
loop
if ST_NumInteriorRings(temp_polygon) > 0 then
temp := array_append(temp, ST_BuildArea(ST_ExteriorRing(temp_polygon)));
else
temp := array_append(temp, temp_polygon);
end if;
end loop;
return ST_Union(temp);
ELSEIF polygon_type = 'POLYGON' then
raise notice '类型-%', polygon_type;
--有内环的,去除内外
if ST_NumInteriorRings(m_polygon) > 0 then
return ST_BuildArea(st_exteriorring(m_polygon));
end if;
end IF;
return m_polygon;
END ;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100
将MultiPolygon基于凹包的方式转为Polygon
基于下面函数可以实现,如果有洞
ST_ConcaveHull(m_polygon,0.1,false);
- 合并前
- 合并后
合并并去除多边形内洞脚本
CREATE OR REPLACE FUNCTION "public"."merge_polygon"("m_polygon" geometry)
RETURNS geometry AS
$BODY$
DECLARE
-- 提取多边形外轮廓
polygon_type text;
BEGIN
polygon_type := GeometryType(m_polygon);
raise notice '类型-%', polygon_type;
--简单
if polygon_type = 'MULTIPOLYGON' then
raise notice '类型-%', polygon_type;
m_polygon:=polygon_remove_hole(m_polygon);
return ST_ConcaveHull(m_polygon,0.1,false);
ELSEIF polygon_type = 'GEOMETRYCOLLECTION' then
raise notice '类型-%', polygon_type;
ELSEIF polygon_type = 'POLYGON' then
raise notice '类型-%', polygon_type;
--有内环的,去除内外
if ST_NumInteriorRings(m_polygon)>0 then
return polygon_remove_hole(m_polygon);
end if;
end IF;
return m_polygon;
END ;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100