2

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?

asked Dec 20, 2018 at 5:32

1 Answer 1

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...
answered Dec 20, 2018 at 6:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.