0

Code

import os
from qgis.core import (
    QgsVectorLayer
)

uri = r"file:\\\C:\Users\imper\Desktop\XYbuffer_tool\Calapan_XYpoints_comma?delimiter={}&crs=epsg:32651&xField={}&yField={}".format(",", "x_long", "y_lat")
vlayer = QgsVectorLayer(uri, "test", "delimited text")

QgsProject.instance().addMapLayer(vlayer)

From the PyQGIS documentaiton https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadlayer.html#vector-layers

Result

No point layer is loaded

exec(open('C:/Users/imper/AppData/Local/Temp/tmpo4j1vq9h.py'.encode('utf-8')).read())

CSV file

name,corner,x_long,y_lat Shell Calapan,1,121°12'07.5"E,13°25'42.6"N

Shell Calapan,2,121°12'09.1"E,13°25'38.8"N Shell

Calapan,3,121°12'06.0"E,13°25'37.6"N Shell

Calapan,4,121°12'04.3"E,13°25'41.5"N

1
  • Added QgsProject line – BallpenMan Feb 22 '20 at 2:39
3

There are several problems. Firstly, you are specifying a UTM coordinate system (epsg:32651) in your QgsDataSourceUri string. The x and y fields of your csv file are clearly geographic coordinates! Try specifying epsg:4326 instead.

Secondly, because your x and y format is Degrees, Minutes and Seconds you must add an additional parameter to your uri string: &xyDms=yes.

Thirdly, you need forward slashes in your file path.

Fourthly, you must include the file extension (.csv) in the file path.

And finally, the last argument in your QgsVectorlayer constructor should be "delimitedtext" with no space.

So your code should look like:

uri = r"file:///C:/Users/imper/Desktop/XYbuffer_tool/Calapan_XYpoints_comma.csv?delimiter={}&crs=epsg:4326&xyDms=yes&xField={}&yField={}".format(",", "x_long", "y_lat")
vlayer = QgsVectorLayer(uri, "test", "delimitedtext")

QgsProject.instance().addMapLayer(vlayer)

When I recreated your csv and used the above code (adapted for my file path), I got the following result:

enter image description here

4
  • Copy! I should have added more instead of copying the code from the documentation. Thank you for the effort! – BallpenMan Feb 22 '20 at 5:37
  • I have used the code but it is not working. It seems like that after the exec(open('C:/Users/imper/AppData/Local/Temp/tmp6ozao9lx.py'.encode('utf-8')).read()) the True does not appear after – BallpenMan Feb 22 '20 at 5:53
  • Added the print line but it's coming out as False. I'll just figure it out. Thanks! – BallpenMan Feb 22 '20 at 6:04
  • @BallpenMan, double check your path, file name etc. I tested the code and it worked fine for me. The only change I made was the path to the csv on my machine. – Ben W Feb 22 '20 at 7:00

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.