Created
February 9, 2016 14:49
-
-
Save johanez/336218bccc8819c7a54c to your computer and use it in GitHub Desktop.
qgis script to add nodes bearigns and diastances as attribute
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
##input_polygons=vector | |
##node_field_name=string | |
from PyQt4.QtCore import * | |
from qgis.core import * | |
# get layer | |
layer = processing.getObjectFromUri(input_polygons) | |
progress.setInfo(node_field_name) | |
print(layer.crs().authid()) | |
crs_geo = layer.crs().geographicFlag() | |
if crs_geo: | |
setInfo("Layer is in LatLong, no distance calculation!") | |
# test what we can do | |
caps = layer.dataProvider().capabilities() | |
# add field for ndoes if not existing | |
if caps & QgsVectorDataProvider.AddAttributes: | |
field_names = [field.name() for field in layer.pendingFields() ] | |
if node_field_name not in field_names: | |
res = layer.dataProvider().addAttributes([QgsField(node_field_name, QVariant.String)]) | |
layer.updateFields() | |
nodes_field_index = (field_names.index(node_field_name)) | |
# iterate over features and calculate node bearing and distances... | |
iter = layer.getFeatures() | |
n_features = layer.featureCount() | |
for feature in iter: | |
# retrieve every feature with its geometry and attributes | |
# fetch geometry | |
geom = feature.geometry() | |
print "Feature ID %d: " % feature.id() | |
if geom.type() == QGis.Polygon: | |
poly = geom.asPolygon() | |
# xy list of first ring of poly, assuming there is only one! | |
xy = poly[0] | |
for i in range(len(poly[0]) - 1): | |
if crs_geo: | |
dist = NA | |
else: | |
dist = round(xy[i].sqrDist(xy[i+1]) /1000., 2) | |
nodes_text = "node==%i: x=%2d, y=%2d, azim=%6.1f, dist=%6.1f km" % (i, xy[i].x(), xy[i].y(), xy[i].azimuth(xy[i+1]), dist) | |
#print(nodes_text) | |
attr = {nodes_field_index : nodes_text} | |
# print(attr) | |
layer.dataProvider().changeAttributeValues({ i : attr }) | |
# fetch & print attributes | |
attrs = feature.attributes() | |
print attrs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment