2

I am new to QGIS, but familiar with Python.

I have one .csv file (Towers_US.csv" ) that contains latitude and longitude of mobile towers of United States (US), and a folder (vectors) with shapefiles of grids for the entire map of US (see image below).

Map of US with mobile towers locations

I have attempted to write the Python script (see the code below) to take as input the locations and loop each shapefile grid and do select by location (within) for each of the grids and save the outputs as shapefiles in the folder vectors_1.

import glob, os, processing

p_layer = "C:/Users/Miro_Saide/Documents/QGIS/US/Towers_US.csv" 
G_layers = "C:/Users/Miro_Saide/Documents/QGIS/US/Files_Qgis/vectors"
output_dir = "C:/Users/Miro_Saide/Documents/QGIS/US/Files_Qgis/vectors/vectors_1"

os.chdir(G_layers)
for fname in glob.glob("*.shp"):

    processing.run("native:selectbylocation", {'INPUT':p_layer,'PREDICATE' [6],'INTERSECT':G_layers,'METHOD':0}) 

I have executed this script but no output is coming. I wonder what could be improved.

2
  • It would be easier to Intersect then "Split vector Layer"
    – BERA
    Jun 18, 2021 at 12:59
  • When I tried this, I am not getting the selected points per grid.
    – Miro Saide
    Jul 5, 2021 at 12:29

1 Answer 1

2

As was mentioned by @BERA you will need firstly to load your layers properly:

For shapefiles:

path_to_shp_layer = "C:/Users/Miro_Saide/Documents/QGIS/US/Files_Qgis/vectors/layer.shp"
vlayer = QgsVectorLayer(path_to_shp_layer, "G_layer", "ogr")

For CSV files:

uri = "file:///C:/Users/Miro_Saide/Documents/QGIS/US/Towers_US.csv?delimiter={}&xField={}&yField={}".format(";", "x", "y")
csvlayer = QgsVectorLayer(uri, "p_layer", "delimitedtext")

And also try 'PREDICATE': [6] instead of 'PREDICATE' [6].

6
  • I tried this but no output is given, I wonder if something must be added in the code so that it will save each selected point in the grid to a shape file?
    – Miro Saide
    Jul 5, 2021 at 12:32
  • Can you please share your data (sample) with us?
    – Taras
    Jul 5, 2021 at 12:33
  • What kind of error are you receiving?
    – Taras
    Jul 5, 2021 at 12:34
  • You can find the data in this google drive link: drive.google.com/file/d/1ZCTKTWZ745_RQPhFA75k1OfExAXeWcT4/…
    – Miro Saide
    Jul 5, 2021 at 13:07
  • I am not getting any error neither output. I wonder how could I use 'qgis:saveselectedfeatures'?
    – Miro Saide
    Jul 5, 2021 at 13:09

Your Answer

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

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