Created
September 30, 2020 11:49
-
-
Save raftx24/645bbfc41f934d1bef9605833740e477 to your computer and use it in GitHub Desktop.
Add points to a line with opengis and pgroute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create function add_points_to_line(line geometry, new_points geometry[]) | |
returns geometry | |
language plpgsql | |
as | |
$$ | |
declare | |
result geometry; | |
begin | |
drop table if exists points; | |
CREATE TABLE points ( | |
"id" serial, | |
"geom" geography NOT NULL, | |
"x" float8, | |
"y" float8, | |
"endpoint" boolean | |
); | |
-- insert line into points tables | |
insert into points (geom, x, y, endpoint) | |
SELECT (dump).geom AS geom,ST_X((dump).geom) AS x,ST_Y((dump).geom) AS y, ((dump).geom = st_startpoint(line) or (dump).geom = st_endpoint (line)) as endpoint | |
FROM (SELECT ST_DumpPoints (line) AS dump) AS xx; | |
-- insert new points into points table | |
insert into points (geom, x,y, endpoint) | |
SELECT p.geom, ST_X(p.geom), ST_Y(p.geom), true FROM unnest(new_points) p(geom); | |
WITH endpoints as ( -- generating starting & ending points | |
select starting_points.id as starting_point_id, ending_points.id as ending_point_id | |
from (select * from points where endpoint = true) as starting_points, (select * from points where endpoint = true) as ending_points | |
where starting_points.id < ending_points.id | |
), | |
lines as ( -- generate lines | |
select ( | |
-- generating line with tsp based on endpoints | |
ST_MAKELINE( | |
ARRAY(SELECT points.geom::geometry FROM pgr_TSPeuclidean ( | |
\'SELECT id,x,y FROM points\', | |
endpoints.starting_point_id, | |
endpoints.ending_point_id | |
) as tsp | |
JOIN points ON points.id = tsp.node | |
where seq <= (select MAX(points.id) from points) -- TSP is closed path therefore we do not include last point | |
ORDER BY seq) | |
) | |
) as geom from endpoints | |
) select (SELECT lines.geom from lines order by ST_LENGTH(lines.geom::geometry) limit 1) into result; | |
return result; | |
end; | |
$$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
adding points to a line with TSP, OpenGIS, pgroute, PostgreSQL