Combining CSV and shapefile to find area name where stations are located

Step 1: Load the CSV into QGIS.

Step 2: Use join attributes by location to add the marine area names to the point data (thus, first layer in dialogue is the stations, second the marine areas).

Step 3: Save your created data & table.


A solution using PyQGIS.

Let's assume there is a project folder with two files: 'test_points.csv' and 'test_polygons.shp', see image below.

input

In QGIS they will look like

qgis

Proceed with Plugins > Python Console > Show Editor and copy&edit&paste the script below

# defining inputs
project_path = 'C:/Users/DUBRTARA/Desktop/test/project/'
csv_file_name = 'test_points.csv'
shp_file_name = 'test_polygons.shp'

# Step 1: reading a csv file with points and converting it into a shapefile
uri_csv_file = 'file:///' + project_path + csv_file_name + "?encoding={0}&delimiter={1}&xField={2}&yField={3}&crs={4}".format("UTF-8",",","x","y","epsg:31469")
# In .format("UTF-8",",","x","y","epsg:31469")
# "UTF-8" stands for data encoding (optional)
# "," is a delimiter used in the input file
# xField is a column name for longitude value
# yField is a column name for latitude value
# crs is a Coordinate system in EPSG number
points = QgsVectorLayer(uri_csv_file, '', "delimitedtext")
if not points.isValid():
    print ("{} layer was not loaded".format(csv_file_name))

# Step 2: reading a shapefile with polygons
path_to_shp_file_name = project_path + shp_file_name
polygons = QgsVectorLayer(path_to_shp_file_name, '', "ogr")
if not polygons.isValid():
    print ("{} layer was not loaded".format(shp_file_name))
    
# Step 3: joining attributes by location and adding it into the QGIS's main window
processing.runAndLoadResults('qgis:joinattributesbylocation', {
                                                'INPUT':points,
                                                'JOIN':polygons,
                                                'DISCARD_NONMATCHING':False,
                                                'JOIN_FIELDS':[],
                                                'METHOD':0,
                                                'PREDICATE':0,
                                                'PREFIX':'_',
                                                'OUTPUT':'memory:'})
# for more details run the following command >>> processing.algorithmHelp("qgis:joinattributesbylocation")

Press Run script run script and get the output that will look like

result


References:

  • Geodose | Python QGIS Tutorial: Adding CSV Data
  • PyQGIS Developer Cookbook » 3. Loading Layers
  • QGIS Docs » 23.1.14.15. Join attributes by location
  • PyQGIS 101: Running Processing tools