I have line and polygon layers. I want to make a list of points' coordinates (ends or begginings of lines), which are touching the polygons. The coordinates which I need are selected as yellow.
With the code I have right now I get coordinates of the whole line. How to change it? Here is the part of the code and visualisation of my result:
lineFeatures = lines.getFeatures()
lakes=[]
for lineFeat in lineFeatures:
lineGeom=lineFeat.geometry()
polygonFeatures=polygons.getFeatures()
for polygonFeat in polygonFeatures:
polyGeom=polygonFeat.geometry()
if lineGeom.touches(polyGeom):
lakes.append(lineGeom.asPolyline()[0])
lakes.append(lineGeom.asPolyline()[1])
The points in the pictures are there just for visualization. In my project, I have only lines and polygons.
I am working with QGIS and python.
From one of the answers, I found a solution. The code below do exactly what I wanted.
lakes=[]
lineFeatures = [feat for feat in lines.getFeatures()]
polyFeatures = [feat for feat in polygons.getFeatures()]
for lineFeat in lineFeatures:
for polyFeat in polyFeatures:
if polyFeat.geometry().intersects(lineFeat.geometry()):
geom = polyFeat.geometry().intersection(lineFeat.geometry())
line_intersection = geom.asPolyline()
if line_intersection:
lakes.append(line_intersection[0])
lakes.append(line_intersection[1])
Answer
Try out with 'intersects' and 'intersection' methods. Next code produces only two points.
mapcanvas = iface.mapCanvas()
layers = mapcanvas.layers()
feats_line = [ feat for feat in layers[0].getFeatures() ]
feats_poly = [ feat for feat in layers[1].getFeatures() ]
for feat_l in feats_line:
for feat_p in feats_poly:
if feat_p.geometry().intersects(feat_l.geometry()):
geom = feat_p.geometry().intersection(feat_l.geometry())
print geom.asPolyline()[0]
print geom.asPolyline()[1]
I tested it with next simple hypothetical situation:
and it works. Points printed at the Python Console were:
(386524,4.45324e+06)
(410342,4.44987e+06)
Editing Note:
With 4 lines:
running this code:
mapcanvas = iface.mapCanvas()
layers = mapcanvas.layers()
feats_line = [ feat for feat in layers[0].getFeatures() ]
feats_poly = [ feat for feat in layers[1].getFeatures() ]
my_list_points = []
for feat_l in feats_line:
for feat_p in feats_poly:
if feat_p.geometry().intersects(feat_l.geometry()):
geom = feat_p.geometry().intersection(feat_l.geometry())
my_list_points.append(geom.asPolyline()[0])
my_list_points.append(geom.asPolyline()[1])
print my_list_points
produces a list with 8 points:
[(387941,4.45518e+06), (410116,4.45158e+06), (385087,4.45128e+06), (411027,4.44466e+06), (383102,4.44575e+06), (408687,4.43823e+06), (392714,4.4348e+06), (405952,4.43338e+06)]
No comments:
Post a Comment