SELECT
torigin1.id AS origin_id,
tdest1.id AS destination_id,
CASE
WHEN ST_LineLocatePoint(troad.line_string, torigin1.geom) < ST_LineLocatePoint(troad.line_string, tdest1.geom)
THEN ST_Length(ST_LineSubstring(troad.line_string,
ST_LineLocatePoint(troad.line_string, torigin1.geom),
ST_LineLocatePoint(troad.line_string, tdest1.geom)
))
ELSE ST_Length(ST_LineSubstring(troad.line_string,
ST_LineLocatePoint(troad.line_string, tdest1.geom),
ST_LineLocatePoint(troad.line_string, torigin1.geom)
))
END AS road_distance
FROM troad
INNER JOIN torigin1 ON troad.gid = torigin1.gid
INNER JOIN tdest1 ON troad.gid = tdest1.gid
WHERE torigin1.gid IN (2) AND tdest1.gid IN (2);
The result I got is not close to the actual distance. All three datasets used are in UTM projection 32644 as the region I worked is in India.
I have tried using ST_ClosestPoint as well but still the answer is not correct.