2

I am in the process of developing a plugin for QGIS and I need to convert an input vector layer (containing a polygon) into GeoDataFrame. The input layer is imported like this:

input_Area = self.dlg.ui.Area.currentLayer()

And I need to use it for the following function (which uses a GeoDataFrame as input):

def create_grid_from_polygon(polygon, grid_size):
    polygon_geom = polygon['geometry']
    bbox = polygon_geom.bounds
    xmin, ymin, xmax, ymax = bbox.minx[0], bbox.miny[0], bbox.maxx[0], bbox.maxy[0]
    #Calculate number of rows and columns
    row = int((ymax-ymin) / grid_size)
    col = int((xmax-xmin) / grid_size)

    #initialize point grid
    grid_layer = []

    for i in range(row):
        for j in range(col):
            #Calculate x and y coordinates of the current point
            x = xmin + j * grid_size
            y = ymin + i * grid_size

            #Create a QgsPointXY object for point
            point = QgsPointXY(x,y)

            #Check if it is within the polygon and add the points within the area
            if polygon.contains(point):
                grid_layer.append(point)
    
    return grid_layer

I have been trying something like this:

features = []
for feature in input_Area.getFeatures():
    features.append(feature)

geometry_col = input_Area.geometry.name()
if geometry_col:
    gdf = gpd.GeoDataFrame(features, geometry=geometry_col)
else:
    print("Geometry column not found")

But I can't really get it to work. It seems to be having trouble finding the name of the geometry column, and here it is important to note that since the code is for a plugin, the code needs to find this name on its own.

If this method isn't possible I'd love any suggestions for another solution.

1
  • You can use geopandas
    – sermomon
    Oct 26, 2023 at 20:56

1 Answer 1

2

GeoPandas can create the GeoDataFrame instance directly from the QGIS features iterator, using the from_features() class method. It will correctly recognize the attributes and geometry.

All you need to do is:

gdf = gpd.GeoDataFrame.from_features(input_Area.getFeatures())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.