I have a vector layer with polygons. There's only 1 attribute – NAME – corresponding to the name of the polygon.
I need to create a new vector layer containing the line segments representing the borders between the polygons. I want each border to be identified by the names of the 2 polygons that meet at that border.
I can get the line segments, and name of one of the polygons, but not the other. Here's my code:
from PyQt4.QtCore import QVariant
vl = QgsVectorLayer("MultiLineString", "Borders", "memory")
pr = vl.dataProvider()
pr.addAttributes([QgsField("NAME1", QVariant.String), QgsField("NAME2", QVariant.String)])
vl.updateFields()
import itertools
layer = qgis.utils.iface.activeLayer()
for geom1,geom2 in itertools.combinations(layer.getFeatures(),r=2):
if geom1.geometry().intersects(geom2.geometry()):
geom = geom1.geometry().intersection(geom2.geometry())
fet = QgsFeature()
fet.setGeometry(geom)
fet.setAttributes(geom1.attributes())
pr.addFeatures([fet])
vl.updateExtents()
QgsMapLayerRegistry.instance().addMapLayer(vl)
How can I obtain attributes of geom2
and add to the NAME2
field in the new vector layer? I know I need to use something like:
for geom1,geom2 in itertools.combinations(layer.getFeatures(),r=2):
if geom1.geometry().intersects(geom2.geometry()):
geom = geom1.geometry().intersection(geom2.geometry())
fet = QgsFeature()
fet.setGeometry(geom)
id1 = provider.fieldNameIndex("NAME")
id2 = provider.fieldNameIndex("NAME")
attribute = [None] * len(pr.fields())
attribute[id1] = geom1.attributes()
attribute[id2] = geom2.attributes()
fet.setAttributes(attribute)
pr.addFeatures([fet])
But this gives me NULL values. How should I change this code?