2

I'm trying to follow the map rendering section from the PyQGIS cookbook. I am able to render a shapefile using qgs vector layer, however getting error prompt while loading delimited text file through qgs vector layer.

enter image description here

My script is (running in QGIS python console)

from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtXml import *

mapinstance = QgsMapLayerRegistry.instance()
mapinstance.removeAllMapLayers()

layer = QgsVectorLayer("f:\scripts\map\wb.shp", "wb", "ogr")

if layer.isValid():
    print "shape layer successfully loaded - adding to map instance"
    mapinstance.addMapLayer(layer)
else:
    print "shape layer failed to load!" 

uri = "f:/scripts/map/points.csv?delimiter=%s&xField=%s&yField=%s" % (",", "longitude", "latitude")
vlayer=QgsVectorLayer(uri,"points","delimitedtext")

if vlayer.isValid():
    print "point layer successfully loaded - adding to map instance"
    mapinstance.addMapLayer(vlayer)
else:
    print "point layer failed to load!"


print mapinstance.mapLayers()
# create image
img = QImage(QSize(800,600), QImage.Format_ARGB32_Premultiplied)
# set image background color
color = QColor(255,255,255)
img.fill(color.rgb())
# create painter
p = QPainter()
p.begin(img)
p.setRenderHint(QPainter.Antialiasing)
render = QgsMapRenderer()
# set layer set
lst = [ layer.id() ] # add ID of every layer
render.setLayerSet(lst)
# set extent
rect = QgsRectangle(render.fullExtent())
#rect.scale(1.39800703)
rect.scale(1.1)
render.setExtent(rect)
# set output size
render.setOutputSize(img.size(), img.logicalDpiX())
# do the rendering
render.render(p)
p.end()

# save image
img.save('f:\scripts\out.png',"png")

and points.csv file contains following data

longitude,latitude

88.3697222,22.5697222

87.3194986,22.3243243
3

You have to write the url that points to the csv as such:

uri =  "file:///f:/scripts/map/points.csv?delimiter=%s&xField=%s&yField=%s" % (",", "longitude", "latitude") 

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.