Index de l'article

Open layers

Open some shapes

# Main path
myPath = r'C:\\Users\\Georges\\Downloads\\'
 
project = QgsProject.instance()
project.removeAllMapLayers()
project.clear()
iface.mapCanvas().refresh()
 
# Path of layers
peaks = QgsVectorLayer(myPath + 'peaks_selection/peaks_selection.shp', 'Sommets', 'ogr')
glaciers = QgsVectorLayer(myPath + 'glaciers/glaciers.shp', 'Glaciers', 'ogr')
eau = QgsVectorLayer(myPath + 'eau/eau.shp', 'Fleuves', 'ogr')
troncons_routes = QgsVectorLayer(myPath + 'troncons_routes/troncons_routes.shp', 'Grandes routes', 'ogr')
iris = QgsVectorLayer(myPath + 'iris/iris.shp', 'IRIS', 'ogr')
 
# Open layers
project.addMapLayer(peaks)
project.addMapLayer(glaciers)
project.addMapLayer(eau)
project.addMapLayer(troncons_routes)
project.addMapLayer(iris)
 
iface.mapCanvas().refresh()

Open OSM

(Attention to the &)

project = QgsProject.instance()
 
urlWithParams = "type=xyz&url=http://tile.openstreetmap.org/{z}/{x}/{y}.png"
osm = QgsRasterLayer(urlWithParams, "OpenStreetMap", "wms")
 
project.addMapLayer(osm)
osm.setOpacity(0.75)
 
iface.mapCanvas().refresh()

As we open OSM, which use a specific projection (3857), better to define and force the projection of the project, and the ellipsoid:

project = QgsProject.instance()
...
crs = QgsCoordinateReferenceSystem.fromEpsgId(4326)
project.setCrs(crs)
project.setEllipsoid('EPSG:4326')

Open a Geojson

Or a GML...

myPath = r'C:\\Users\\georg\\Downloads\\'
 
project = QgsProject.instance()
 
eau = QgsVectorLayer(myPath + 'MyGeoJson.geojson', 'Rivières', 'ogr')
 
project.addMapLayer(eau)

Open a Geojson online

iface.addVectorLayer('https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_50m_populated_places.geojson', 'Populated places', 'ogr')

Change a layer's encoding

myLayer = QgsVectorLayer(r'C:/Users/Georges/Downloads/my layer/new_file.tab', new_file, 'ogr')
myLayer.setProviderEncoding('ISO-8859-1')

Open a CSV

csv_path = 'file:///' + myPath + 'World Stats.csv?delimiter=;'
my_csv = QgsVectorLayer(csv_path, 'Countries', 'delimitedtext')
project.addMapLayer(my_csv)