[GIS] PyQGIS standalone script: how to join attributes by location

pyqgisspatial-joinstandalone

I'm writing a stand-alone script using no GUI.

Earlier I posted a question about having some code issues using JoinAttributes function. However, I found out that the function is not appropriate for my needs. I'm looking for a function that would add attributes of a poligon layer features to point features that lay on it (exactly like the function Join attributes by location in QGIS). I found an earlier answer suggesting to use modules shapely and fiona. However, I would like to avoid external libraries in this application.

Is there any PyQGIS function that would do the trick in a stand-alone script?

Best Answer

The following script works well for me (make sure your PATHS are correctly set):

from qgis.core import *
from qgis.utils import *
import os, sys

QgsApplication.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
app = QApplication([], True)
QgsApplication.initQgis()

sys.path.append('C:/OSGEO4~1/apps/qgis/python/plugins')
from processing.core.Processing import Processing
Processing.initialize()
from processing.tools import *

layer1 = "path/to/point_shapefile.shp"
layer2 = "path/to/polygon_shapefile.shp"
result = "path/to/output_shapefile.shp"

general.runalg("qgis:joinattributesbylocation", layer1, layer2, u'intersects', 0, 0, '', 1, result)