I know that there are already many questions regarding this matter. In fact, I have already seen the following questions:
- How to load a WMS layer using PyQGIS?
- Adding a WMS layer in QGIS using python
- Load WMS with PyQGIS
- WMS layer in a QGIS 2.4 stand alone Python script
- How to open a specific WMS layer in QGIS with a single URL?
I am working on making a plugin for QGIS 2.18 using python 2.7 on Windows. Here is my code:
wms_url="http://localhost/MapServer/mapserv.exe?map=c:/inetpub/wwwroot/data//Mapfile.map&request=GetMap&service=WMS&version=1.3.0&layers=Region_Map&width=480.000&height=480.000&format=image/png&bbox=8.473957,77.262417,8.519412,77.307871&crs=EPSG:4326&styles=" wms_url = wms_url + "&styles=" print(wms_url) # setting prefix path of qgis # TODO: get this path dynamically qgis_prefix = "C:\\OSGeo4W64\\apps\\qgis-ltr" QgsApplication.setPrefixPath(qgis_prefix, True) QgsApplication.initQgis() #adding the WMS Layer rlayer = QgsRasterLayer(wms_url, 'default map', 'wms, True) print(rlayer.isValid()) if(rlayer.isValid): QgsMapLayerRegistry.instance().addMapLayer(rlayer) else: print(rlayer.error().message())
Once this code is executed, the following messages are seen:
Raster layer: Provider is not valid (provider: wms, URI: http://localhost/MapServer/mapserv.exe?map=Mapfile.map&request=GetMap&service=WMS&version=1.3.0&layers=Layer&width=480.000&height=480.000&format=image/png&bbox=8.473957,77.262417,8.519412,77.307871&crs=EPSG:4326&styles=
(The second line contains a u' and followed by a p and b tad at the start of the statement in the console; I am unable to show it exactly here)
Download of capabilities failed: Protocol "" is unknown)
Based on the answers I read, I have also tried the following:
- Changing the url to
- Clearing the QGIS cache
- Adding the prefix path to
QgsApplication(evident from the code).
I should also add that this url works perfectly when run on web browser or if the url
http://localhost/MapServer/mapserv.exe?map=Mapfile.map is added to "Add WMS/WMTS Layer" (GUI option). Also, if I remove the
'wms' in the above code, then an image is added, although it does not get loaded to the correct dimensions.
Is there something else that I am missing?
Some Additional Info
From the following link pyQGIS Developer Cookbook
Alternatively you can load a raster layer from WMS server. However currently it’s not possible to access GetCapabilities response from API — you have to know what layers you want:
urlWithParams = 'url=http://irs.gis-lab.info/? layers=landsat&styles=&format=image/jpeg&crs=EPSG:4326' rlayer = QgsRasterLayer(urlWithParams, 'some layer name', 'wms') if not rlayer.isValid(): print "Layer failed to load!"
This suggests that the first parameter should be the full URL to the WMS request with the provider being
'wms' as visible in the code above.