In my QGIS python plugin I want to add a background map (if the user haven't added one), hence I think I missing something in the url for the Tiles/wms service.. (the function returns invalid layer
) Any suggestions?
sources = [layer.source() for layer in QgsProject.instance().mapLayers().values()]
print(sources)
source_found = False
for source in sources:
if 'xyz&url' in source:
source_found = True
print('found')
if not source_found:
print('adding')
urlWithParams = 'type=xyz&url=http://a.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857'
rlayer = QgsVectorLayer(urlWithParams, 'OpenStreetMap', 'wms')
if rlayer.isValid():
QgsProject.instance().addMapLayer(rlayer)
else:
print('invalid layer')
axel_andeaxel_ande
asked Aug 11, 2018 at 7:18
-
1What version of QGIS, are you using ?Ahsan Mukhtar– Ahsan Mukhtar2018年08月11日 07:39:11 +00:00Commented Aug 11, 2018 at 7:39
-
QGIS3.. (I know how to add it with XYZ Tiles manually)axel_ande– axel_ande2018年08月11日 14:01:47 +00:00Commented Aug 11, 2018 at 14:01
-
python to load xyz tiles raw.githubusercontent.com/klakar/QGIS_resources/master/… > sources.append(["connections-xyz","OpenStreetMap Standard"Mapperz– Mapperz ♦2018年08月15日 04:32:10 +00:00Commented Aug 15, 2018 at 4:32
-
I know, it is a very nice script how to add the tiles to the browser, hence I would like to add it as a layer.axel_ande– axel_ande2018年08月15日 07:48:56 +00:00Commented Aug 15, 2018 at 7:48
1 Answer 1
Tiles/WMS sources give you raster data. So, you have to use QgsRasterLayer()
instead of QgsVectorLayer()
.
Try in this way:
...
rlayer = QgsRasterLayer(urlWithParams, 'OpenStreetMap', 'wms') # EDIT THIS LINE
if rlayer.isValid():
QgsProject.instance().addMapLayer(rlayer)
else:
print('invalid layer')
answered Aug 21, 2018 at 7:20
-
I knew it was an easy fix! Thxaxel_ande– axel_ande2018年08月21日 08:57:15 +00:00Commented Aug 21, 2018 at 8:57
lang-py