I'm trying to use the python console to import some gpx files as vector layers. When I do it manually I have to choose which layers to add, my options are:

Select vector layers to add image

I've tried various versions of the code from the manual:

uri = "path/to/gpx/file.gpx?type=track"
vlayer = QgsVectorLayer(uri, "layer name you like", "gpx")

I also tried adding the layer name I want like:

path/to/gpx/file.gpx|layername=track_points?type=track", "layer name you like", "gpx")

Edit: On each try I don't get any errors, it just doesn't import anything, ie no new layers in the layers panel. I would like to import the files using python as I have quite a large number of them. I could do it manually but I would have to choose the track_points layer for each file

Edit: From Joseph's answer I adapted his code and got what I wanted, not entirely sure how but if it helps anyone else:

import os
path = 'Path/To/GPX Files/'
names = ["track_points"]
for dirpath, subdirs, files in os.walk(path):
    for f in files:
    layername = f[:-4]
        for name in names: 
            iface.addVectorLayer(os.path.join(dirpath, f)+"?type="+name, layername, "gpx")
  • Welcome to GIS SE! As a new user please take the tour which describes how this site works, Precisely what happened when you tried each of these things? And what is the question you wish to pose to users of this site? – PolyGeo Feb 4 '16 at 10:35
  • Please use the edit button beneath your question to revise it with any requested clarifications. – PolyGeo Feb 4 '16 at 11:20
  • 1
    When you have loaded the layers manually, save each of them as layer file. Use a file editor to inspect the layer file and look for the uri string. This is the string you have to pass from pyqgis to load one out of several layers from such multi layer datasources. – Detlev Feb 4 '16 at 14:11

This is only half an answer as the following code can be used to import waypoints, routes and tracks but not route_points or track_points (these seem to be replaced by the tracks layer).

import os

path = "path/to/gpx/folder"
names = ["waypoint", "route", "track", "route_point", "track_point"]

for dirpath, subdirs, files in os.walk(path):
    for f in files:
        for name in names:
            iface.addVectorLayer(os.path.join(dirpath, f)+"?type="+name, name, "gpx")

Not sure how to import the last two layers using PyQGIS. The code was adapted from this useful post:

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.