Last active
August 29, 2015 14:08
-
-
Save fitnr/5ad46a7c59db143cfc4e to your computer and use it in GitHub Desktop.
Create a complete graph of lines between a set of points in QGIS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import combinations | |
# get the active layer | |
inlayer = iface.activeLayer() | |
# Get the index of the NAME field, then rewind the list | |
infeatures = inlayer.getFeatures() | |
eg = infeatures.next() | |
i = eg.fields().indexFromName('NAME') | |
infeatures.rewind() | |
# get the active layer's crs | |
crs = inlayer.crs().geographicCRSAuthId() | |
# create the new layer and start editing it | |
defstring = "LineString?crs=" + crs + "&field=id:integer&field=from:string(20)&field=to:string(20)&index=yes" | |
layer = QgsVectorLayer(defstring, "complete_graph", "memory") | |
layer.startEditing() | |
# Get every combination of points | |
pairs = combinations(infeatures, 2) | |
n = 0 | |
for start, end in pairs: | |
if start == end: # don't create lines with length 0 | |
continue | |
# hey, this API isn't super-simple | |
startgeo, endgeo = start.geometry().asPoint(), end.geometry().asPoint() | |
line = QgsGeometry.fromPolyline([QgsPoint(*startgeo), QgsPoint(*endgeo)]) | |
# Add feature to layer | |
feature = QgsFeature() | |
feature.setGeometry(line) | |
feature.setAttributes([n, start.attributes()[i], end.attributes()[i]]) | |
layer.dataProvider().addFeatures([feature]) | |
# use this for testing | |
#n = n + 1 | |
#if n > 10: | |
# break | |
layer.updateExtents() | |
layer.commitChanges() | |
QgsMapLayerRegistry.instance().addMapLayer(layer) | |
print 'layer is valid:', layer.isValid() | |
error = QgsVectorFileWriter.writeAsVectorFormat( | |
layer, | |
"/full/path/to/a/file/complete.shp", | |
"CP1250", | |
None, | |
"ESRI Shapefile" | |
) | |
if error == QgsVectorFileWriter.NoError: | |
print "success!" | |
else: | |
print 'error' | |
print error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment