In this algorithm I need to create points inside every polygon. The easy solution I was thought was using the centroid. With some help of the community we reach in this algorithm
from qgis.PyQt.QtGui import * from qgis.PyQt.QtCore import * import processing source_layer = iface.addVectorLayer("folder/Polygon.shp", "Setor", "ogr") crs = source_layer.crs().toWkt() # Define additional attributes already on the layer level centroid_layer = QgsVectorLayer('Point?field=cd_geocodi:string&crs=' + crs, 'MyPoint' , 'memory') centroid_layer.startEditing() # Loop over all features points = 50 p = 1 while p <= points: #reading every feature and getting those centroid and one attribute for source_feature in source_layer.getFeatures(): geometry = source_feature.geometry() centroid = geometry.centroid() name = source_feature.attribute("CD_GEOCODI") # select the attribute # Create the new feature with the fields of the memory layer # And set geometry and attribute before adding it to the target layer centroid_feature = QgsFeature(centroid_layer.fields()) centroid_feature.setGeometry(centroid) centroid_feature['cd_geocodi'] = name centroid_layer.addFeature(centroid_feature) p += 1 centroid_layer.commitChanges() # Add the layer to the registry QgsMapLayerRegistry.instance().addMapLayer(centroid_layer) #https://docs.qgis.org/2.8/en/docs/user_manual/processing_algs/qgis/vector_analysis_tools/countpointsinpolygonweighted.html #counting points inside polygons Result = "folder/output.shp" processing.runalg("qgis:countpointsinpolygon", source_layer, centroid_layer, 'NUMPOINTS', Result) iface.addVectorLayer(Result, 'result', 'ogr')
But depending on how unusual is the polygon the centroid is calculated in other polygon, like below:
I found answers like https://gis.stackexchange.com/a/259185/104521 who makes me think about create a
for inside another
for, to use some similar logic to filter the polygon area and insert a random point inside. I had try to adapt these algorithms, but I did not make it. Probably because my skills are limited.
Can someone help me?