3

I have a parcels shapefile that contains polygons. Condos are also drawn, but inside the master lot. I want to be able to grab all the condos inside the master lot. I saw this question/answer: Finding all polygons inside of a polygon, but that is for POSTGIS and I'm working with shapefiles. I'm writing a plugin for owners lists, so I need this type of search to be included in order to get a complete owners list. The spatial query doesn't allow a search on the same layer which is a problem.

The basic question is: How do I select polygons inside polygons within the same shapefile?

1 Answers1

1

You could use a custom script containing the following function which essentially:

  1. Let's you select the master lot (in case you have more than one in your shapefile).
  2. Uses a spatial index to add all features (which intersect the master lot) to a list.
  3. Deselects the master lot.
  4. Selects all features which lie inside the master lot.

You can create a script from:

Processing Toolbox > Scripts > Tools > Create new script

Then use something like the following:

##Select_within_polygons=name
##Polygon_layer=vector polygon

from qgis.core import QgsSpatialIndex

layer = processing.getObject(Polygon_layer)

# Create spatial index
index = QgsSpatialIndex()
# Get master lot
m_lot = layer.selectedFeatures()
for f in m_lot:
    master_lot = f
# Iterate through all features and add to index
for feat in layer.getFeatures():
    index.insertFeature(feat)
    # List to find features which intersect master lot 
    id_list = index.intersects(master_lot.geometry().boundingBox())
# Remove master lot from list
id_list.remove(master_lot.id())
# Deselect master lot
layer.deselect(master_lot.id())
# Select features from id_list
layer.setSelectedFeatures(id_list)

Make sure the script is saved in your /.qgis2/processing/scripts/ directory. Before you run the script, select the master lot from your layer.


Example:

  1. A simple polygon containing smaller polygons inside.

    Before running script


  1. Now we select the bigger polygon:

    Selecting master lot


  1. Then run the script to see the selected polygons inside:

    Result

Joseph
  • 75,746
  • 7
  • 171
  • 282