I have a polygon layer with one polygon and a line layer with a lot of lines. I need to check lines lie on the polygon boundaries or not and if they are add them into a graph. I couldn't think of anything better that convert polygon boundaries to a line layer and I tried to write such code to build a graph but it doesn't work. In fact I need to add polygon boundaries to a graph.
How can I do this?
import networkx as nx
from qgis.core import *
import processing
from shapely.geometry import Polygon, Point, LineString
from shapely.ops import unary_union
polygon_layer = QgsProject.instance().mapLayersByName("polygon")[0]
polygon_feature = polygon_layer.getFeature(0)
polygon = Polygon(polygon_feature.geometry().asMultiPolygon()[0])
polygons = [p for p in polygon_feature.geometry().asMultiPolygon()]
selected_polygon = Polygon(polygons[0][0])
G = nx.Graph()
for vertex in selected_polygon.exterior.coords:
G.add_node(vertex)
temp_lines = processing.run("native:polygonstolines", {'INPUT': polygon_layer, 'OUTPUT':'TEMPORARY_OUTPUT'})["OUTPUT"]
QgsProject.instance().addMapLayer(temp_lines)
for node1 in G.nodes:
for node2 in G.nodes:
if node1 != node2:
line = LineString([node1, node2])
for feature in temp_lines.getFeatures():
geom = feature.geometry().asMultiPolyline()
if line.within(geom):
G.add_edge(node1, node2, weight=Point(node1).distance(Point(node2)))
I also tried to convert polygon to lines, explode it through PyQGIS and then add it into graph, but I got incorrect geometry error (Too few point).
For example, I have such a polygon (red) and lines (blue). And I need to select only boundaries lines (yellow) or both inside and boundaries lines and add them into a graph. I don't need lines outside or partly outside the polygon.