Tuesday 26 December 2017

pyqgis - QGIS GRASS maximum distance to a given feature


I want to calculate the maximum distance between a point and the boundary of a polygon (representing an animal's home range).


Here is an example of the point layer, always within the polygon layer: enter image description here


When I needed the minimum distance, I used "QGIS GRASS > v.distance > minimum distance to nearest feature".


Does anyone know how to calculte the maximum distance in QGIS/GRASS?



Answer



You probably need the maximum minimum distance between all your values. For this reason you don't have available this option in v.distance. However, it's not very difficult to determinate it in QGIS by using PyQGIS. Next code does the work (in your case change the names of respective shapefiles):


registry = QgsMapLayerRegistry.instance()


points = registry.mapLayersByName('Random points')
polygon = registry.mapLayersByName('polygon2')

feats_point = [ feat for feat in points[0].getFeatures() ]
feat_polygon = polygon[0].getFeatures().next()

geom_polygon = feat_polygon.geometry().asPolygon()

geom_polygon_line = QgsGeometry.fromPolyline(geom_polygon[0])


distances = [ feat.geometry().distance(geom_polygon_line)
for feat in feats_point ]

print min(distances), distances.index(min(distances))
print max(distances), distances.index(max(distances))

I ran above code with the shapefiles of next image. At the Python Console of QGIS were printed "minimum" and "maximum" distances for comparison purposes. Indices of respective points were also printed for corroborating the correct code execution. For this reason it could be selected these features (yellow color) at next image.


enter image description here


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...