1

I have a bunch of .csv files with coordinates and a polygon. In my standalone script I would like to check if the polygon intersects with the coordinates.

So, when I write:

            for feature in polygon.getFeatures():
                if feature.geometry().intersects(file.geometry()):

It doesn't work because the coordinates in my 'file' are of type string and not a QGIS Rectangle.

I can use numpy to sort of get the extent of the coordinates as string by writing:

        data = np.genfromtxt(file, delimiter=" ")
        x = data[:, 0]
        y = data[:, 1]

        xmin = min(x)
        xmax = max(x)
        ymin = min(y)
        ymax = max(y)

I feel like I have all the extents but now I need to find a way to check if they intersect. I'm stuck at this point. How can I do this?

I'm using QGIS 3.10.

1 Answer 1

2

You can create a map layer from each CSV file (read the docs).

import glob

for file_path in glob.glob("/path/to/csv/folder/*.csv"):
    uri = "file://{}?delimiter=;&crs=epsg:3116&xField=x&yField=y".format(file_path)
    csv_layer = QgsVectorLayer(uri, file_path, 'delimitedtext')

Then (still inside that for) you can get each layer's extent and check the intersection.

for polygon_feature in polygon_layer.getFeatures():
    if polygon_feature.geometry().intersects(csv_layer.extent()):
        print("File '{}' intersects!".format(csv_layer.name()))       

Note: You seem to have a polygon layer and not just one polygon geometry. If that's the case you'll end up with nested for loops. Otherwise, if you have a single polygon geometry, you will just need a single for to iterate csv files.

3
  • Thanks for the advice, I will try that. However, do we know anything about the time cost it takes to convert text to QgsVectorLayer objects? I was hoping to keep the text format to keep computation time as low as possible.
    – DGIS
    Commented Jul 13, 2020 at 14:32
  • 1
    Well, you could also read each file, parse its coordinates (or perhaps just use the numpy method you mentioned), then make sure you create a proper extent (QgsRectangle) for your csv points, and finally check the intersection. In fact, you could also test the intersection against the BBOX of your polygon to make things a bit faster (that could be done even without a csv BBOX, just dealing with numbers). How to build a QgsRectangle is described here, if that's what you were looking for initially. Commented Jul 13, 2020 at 14:57
  • Thanks, I will look into it. Your first suggestion works fine and I think its fast enough actually. I'll still check the QgsRectangle option though.
    – DGIS
    Commented Jul 13, 2020 at 16:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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