Skip to main content
2 of 3
edited tags
PolyGeo
  • 65.4k
  • 29
  • 114
  • 345

Remove points outside of polygon but keep points with the same feature/ID

I am new to using python in QGIS. I have basic coding and QGIS knowledge, but do not know how to combine it yet.

I have a polygon layer and a point layer. The point layer has specfic features in its table such as an ID called "fwg_type". There can be several points with the same "fw_type".

I would like to remove all the points which lie outside the polygon except the points which share the same ID of points, which lie inside the layer boundaries.

So if points with ID 1 lie inside and outside the layer, the would not be removed.

Here is my script. It does not work yet.. Any ideas?

# Replace 'point_layer' and 'polygon_layer' with the actual names of your layers
point_layer = QgsProject.instance().mapLayersByName('point_layer')[0]
polygon_layer = QgsProject.instance().mapLayersByName('polygon_layer')[0]

# Create a set to store the IDs of points within the polygon
ids_within_polygon = set()

# Iterate through the features in the polygon layer and store their IDs
for feature in polygon_layer.getFeatures():
    ids_within_polygon.add(feature['ID'])  # Replace 'ID' with the actual field name

# Create a new memory layer to store the filtered features
new_layer = QgsVectorLayer("Point?crs=" + point_layer.crs().authid(), "Filtered Points", "memory")
new_layer.startEditing()

# Define the attributes and fields for the new layer
new_layer.dataProvider().addAttributes(point_layer.fields())
new_layer.updateFields()

# Create a list to store the features to keep
features_to_keep = []

# Iterate through the features in the point layer
for feature in point_layer.getFeatures():
    if feature['ID'] in ids_within_polygon or feature['ID'] not in ids_within_polygon:
        features_to_keep.append(feature)

# Add the features to keep to the new layer
new_layer.addFeatures(features_to_keep)
new_layer.commitChanges()

# Add the new layer to the QGIS map
QgsProject.instance().addMapLayer(new_layer)