1

I've two linestrings Line1,Line2. I'm trying to get the part of Line1 that is 300m apart from line2.

line1 = "LINESTRING(72.863221 18.782499,72.863736 18.770147,72.882275 18.756169,72.881417 18.750805,72.878842 18.736987,72.874379 18.709512,72.860989 18.679593,72.864422 18.653897)"
line2 = "LINESTRING(72.883133 18.780793,72.882103 18.760314,72.862534 18.716422,72.860474 18.683577)"

I used the ST_DWithin function but it returns the whole linestring if the distance is lesser than 300 meters. Here's my query:

road2 = "ST_GeographyFromText('SRID=4326;%s')"%line1
road4 = "ST_GeographyFromText('SRID=4326;%s')"%line2
cur.execute("SELECT ST_AsText(road1) from %s as road1,%s as road2 
            where ST_DWithin(road1,road2,500)"%(road2,road4))
res = cur.fetchall()
print res

Can anyone tell me what I'm doing wrong ?

1 Answer 1

2

You can use a combination of ST_Intersection/ ST_Buffer and ST_DWITHIN:

DROP TABLE IF EXISTS LINES;
CREATE TABLE LINES(gid serial, geom geometry(LINESTRING,4326));
INSERT INTO LINES (geom) VALUES(
(ST_SETSRID(ST_GEOMFROMTEXT('LINESTRING(72.863221 18.782499,72.863736 18.770147,72.882275 18.756169,72.881417 18.750805,72.878842 18.736987,72.874379 18.709512,72.860989 18.679593,72.864422 18.653897)'),4326))),
(
(ST_SETSRID(ST_GEOMFROMTEXT('LINESTRING(72.883133 18.780793,72.882103 18.760314,72.862534 18.716422,72.860474 18.683577)'),4326))
);


-- visualizing Buffer
INSERT INTO LINES (geom) VALUES(
(
SELECT ST_Transform(ST_Exteriorring(ST_Buffer(ST_Transform(geom,32643),300)),4326) from LINES where gid=2)
);



-- Intersection

DROP TABLE IF EXISTS Intersection;

CREATE TABLE Intersection(gid serial, geom geometry(MULTILINESTRING,4326));

INSERT INTO Intersection (geom) VALUES(

(
select 
    st_transform(
      st_intersection(
        line1.geom, 
        st_buffer(ST_Transform(line2.geom,32643),300))
      ,
      4326) as geom

from 
  (SELECT ST_Transform(geom,32643) as geom from lines where gid=1) as line1, 
  (SELECT ST_Transform(geom,32643) as geom from lines where gid=2) as line2

where 
  st_dwithin(line1.geom, line2.geom, 300) 
 )
  );

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.