0

I need to achieve exactly what the below script written by Jacob (found here) does, with the addition that I only want to count the points if column B in the point layers attribute field is greater then zero.

Since I'm a rookie with Python I can't figure out how to re-write the code to do that!?

from qgis.core import *
from qgis.gui import *
from qgis.utils import iface

@qgsfunction(args="auto", group='Custom')
def countPointsInCurrentAltlasFeature(pointLayerName, geomAtlas, feature, parent):
    # If point geom is empty, return 0
    if (geomAtlas is None):
        return 0

    # Get point layer reference from layername
    pointLayer = QgsMapLayerRegistry.instance().mapLayersByName(pointLayerName)[0]

    # Raise if layer not found
    if pointLayer is None:
        raise Exception("Layer not found: " + pointLayerName)

    # Count point within current Atlas feature
    countPoint = 0
    for pointFeature in pointLayer.getFeatures():
        pointGeom = pointFeature.geometry()
        if (pointGeom is None):
            continue
        if pointGeom.within(geomAtlas):
            countPoint += 1

    return countPoint

I've tried to change the last countPoint += 1 to IF column "B" > 0 THEN countPoint += 1 but the script wont run and the error doesn't provide any guidance.

1

To get the field attribute use something like pointFeature['fieldname'], try this:

for pointFeature in pointLayer.getFeatures():
    pointGeom = pointFeature.geometry()
    if (pointGeom is None):
        continue
    if pointGeom.within(geomAtlas):
        if pointFeature['B'] > 0: # include field name within quotes
            countPoint += 1

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.