TransWikia.com

Taking line substring from pgr_withpoints output

Geographic Information Systems Asked by Kerry on March 26, 2021

I want to compute the shortest route through a network between two arbitrary points along edges in the network and then get the line substring for that route. I have achieved this with the code below but it only works when the line fraction corresponding to the starting point is smaller than the line fraction corresponding to the end point due to the requirements of the ST_LineSubstring() function.

I know that I could use the least() and greatest() functions to get around this but I won’t know from the output if the start and endpoints have been switched. I would also like to reverse the order of the vertexes with ST_Reverse() in cases where the order of the start and end point have been reversed.

Is there a way to do this which would produce output indicating whether the order of vertices was reversed while also performing this reversal?

CREATE TEMP TABLE temp(pid serial, edge_id bigint, fraction float);

INSERT INTO temp(edge_id, fraction) VALUES 
  (<STARTING EDGE ID>, <STARTING EDGE FRACTION>), 
  (<ENDING EDGE ID>, <ENDING EDGE FRACTION>); 

WITH route AS (
  SELECT * FROM pgr_withPoints(
    'select id, source, target, the_geom, cost from edges',
    'select pid, edge_id, fraction from temp', 
    -1, -2, directed => false)
),

edges_geom AS (
  SELECT * FROM edges, route WHERE edges.gid=route.edge
),

edges_union AS ( 
  SELECT ST_LineMerge(ST_Union(the_geom)) AS geom FROM edges_geom
),

startFrac AS (SELECT ST_LineLocatePoint(
  (SELECT geom FROM edges_union),
  ST_LineInterpolatePoint(
    (SELECT the_geom FROM ways WHERE gid=<STARTING EDGE ID>), 
    <STARTING EDGE FRACTION>
  )
)),

endFrac AS (SELECT ST_LineLocatePoint(
  (SELECT geom FROM edges_union),
  ST_LineInterpolatePoint(
    (SELECT the_geom FROM ways WHERE gid=<ENDING EDGE ID>), 
    <ENDING EDGE FRACTION>
  )
))

SELECT ST_LineSubstring(
  geom, 
  (SELECT * FROM startFrac),
  (SELECT * FROM endFrac)
) FROM edges_union;

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP