2

I have Two layers one is point another is line as indicated in picture.

enter image description here

I want to know they way that i can detect that point is contains/intersect/near to the line so that I can add it's attribute data into line attribute data. As you can see that neither line contains the point nor line intersect the point. So how to get that point? Like point under the bounding box of line etc

  • I think that the most satysfing solution will be to find the nearest neighbour and check if distance between them is less than tolerance. – dmh126 Oct 4 '16 at 11:24
  • how to check neighbour? – Muhammad Faizan Khan Oct 4 '16 at 11:25
  • I'm going to add an answer with that. – dmh126 Oct 4 '16 at 11:26
  • To check neighborhood you can use 'distance' method of QgsGeometry (see my answer). – xunilk Oct 5 '16 at 9:45
3

Code to find the nearest line to each point:

layer_lines # QgsVectorLayer
point # QgsPoint

spi = QgsSpatialIndex()

for feature in layer_lines.getFeatures():
    spi.insertFeature(feature)

print spi.nearestNeighbor(point,1)

I've used here: http://www.qgis.org/api/classQgsSpatialIndex.html

Script prints which line (index) is closest to the point (of course you have to iterate over all points in your final script). So if you have a line index, you should then check if a distance between them is less than tolerance, if true update values, else do nothing.

| improve this answer | |
1

Next code prints (at the Python Console of QGIS) indices (from point and line layers) and minimum distances for each feature involved in each layer.

registry = QgsMapLayerRegistry.instance()

points = registry.mapLayersByName('Random points')
lines = registry.mapLayersByName('lines')

feat_lines = [ feat for feat in lines[0].getFeatures() ]
feat_points = [ feat for feat in points[0].getFeatures() ]

for i, feat_point in enumerate(feat_points):
    distances = []
    for j, feat_line in enumerate(feat_lines):
        distances.append(feat_point.geometry().distance(feat_line.geometry()))
    print i, distances.index(min(distances)), min(distances)

I tried out my code with shapefiles of next image:

enter image description here

All values were corroborated and they were as expected. For convenience, it is preferable to add these values to the attributes table of points layer instead of the line layer.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.