1

I'm trying to extract lat longs from my centroids, then feed the lat longs to the Google distance matrix API using another python script. I exported the graphical model as a python script:

##Drive Time=name
##GridSpacingInMeters=number1000
##Extent=extent
##CentroidsWGS84=output vector
##GridWGS84=output vector
outputs_QGISVECTORGRID_1=processing.runalg('qgis:vectorgrid', Extent,GridSpacingInMeters,GridSpacingInMeters,0,None)
outputs_QGISREPROJECTLAYER_1=processing.runalg('qgis:reprojectlayer', outputs_QGISVECTORGRID_1['OUTPUT'],'EPSG:4326',GridWGS84)
outputs_QGISPOLYGONCENTROIDS_1=processing.runalg('qgis:polygoncentroids', outputs_QGISREPROJECTLAYER_1['OUTPUT'],None)
outputs_QGISEXPORTADDGEOMETRYCOLUMNS_1=processing.runalg('qgis:exportaddgeometrycolumns', outputs_QGISPOLYGONCENTROIDS_1['OUTPUT_LAYER'],0,CentroidsWGS84)

Then I added more lines to the above to create a list of the coordinates, but I'm getting a IndexError: list index out of range

name = 'CentroidsWGS84'
layer = QgsMapLayerRegistry.instance().mapLayersByName(name)[0]
features = layer.getFeatures()
attributes = []
coords = []

for feature in features:
    atributes.append(feature.attributes())

for attribute in attributes:
    coords.append(attribute[5:7])

I suspect this is because the layers that I'm creating on the graphical modeler is not created yet. How do I solve this?

0

you can access the layer through the variable outputs_QGISPOLYGONCENTROIDS_1 which is a dictionary (holding the path to the shapefile from your processing step) and the QgsVectorLayer Class:

##Drive Time=name
##GridSpacingInMeters=number1000
##Extent=extent
##CentroidsWGS84=output vector
##GridWGS84=output vector
from qgis.core import QgsVectorLayer

outputs_QGISVECTORGRID_1=processing.runalg('qgis:vectorgrid',  Extent,GridSpacingInMeters,GridSpacingInMeters,0,None)
outputs_QGISREPROJECTLAYER_1=processing.runalg('qgis:reprojectlayer', outputs_QGISVECTORGRID_1['OUTPUT'],'EPSG:4326',GridWGS84)
outputs_QGISPOLYGONCENTROIDS_1=processing.runalg('qgis:polygoncentroids', outputs_QGISREPROJECTLAYER_1['OUTPUT'],None)
outputs_QGISEXPORTADDGEOMETRYCOLUMNS_1=processing.runalg('qgis:exportaddgeometrycolumns', outputs_QGISPOLYGONCENTROIDS_1['OUTPUT_LAYER'],0,CentroidsWGS84)

data_source = outputs_QGISPOLYGONCENTROIDS_1['OUTPUT_LAYER'] #access the datasource
layer = QgsVectorLayer(data_source, 'centroids', 'ogr')
#here comes your code...

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.