Sunday, 25 March 2018

Add OpenLayers layer from QGIS's Python console?


On QGIS 2.4.0-Chugiak the Openlayers plugin is found under Web menu rather than the Plugins menu. How can you use the Python console to add a Openlayers Google Maps layer?


The following code give us the error OpenLayers plugin not loaded.


try:
olplugin = qgis.utils.plugins['openlayers']
ol_gphyslayertype = olplugin.olLayerTypeRegistry.getById(0)
olplugin.addLayer(ol_gphyslayertype)
except KeyError:

print 'OpenLayers plugin not loaded.'

Answer



Using the direct way as you tried in your example looks much cleaner, however, I did not find out either how to achieve this in QGIS 2.4.


So long, as a workaround, you can navigate through the menu interface manually to open the desired map from the OpenLayers plugin. In the following code, set the variables mapProvider and openLayersMap to your desired entries from the QGIS->Web->OpenLayers plugin menu. See inline comments for further explanation.


mapProvider = 'Google Maps' #also use e.g. 'OpenStreetMap', 'Bing Maps' etc. as given in the Web->OpenLayers plugin menu
openLayersMap = 'Google Physical' #also use e.g. 'Google Streets', 'OpenStreetMap', 'Bing Road' etc. as given in the Web->OpenLayers plugin menu

webMenu = qgis.utils.iface.webMenu() #get object of the Web menu of QGIS

for webMenuItem in webMenu.actions(): #open the Web menu of QGIS and loop through the list of web plugins

if 'OpenLayers plugin' in webMenuItem.text(): #look for OpenLayers plugin entry in the Web menu
openLayersMenu = webMenuItem #and open it

for openLayersMenuItem in openLayersMenu.menu().actions(): #open the OpenLayers plugin menu entry and loop through the list of map providers
if mapProvider in openLayersMenuItem.text(): #if the desired mapProvider is found
mapProviderMenu = openLayersMenuItem #open its menu entry

for map in mapProviderMenu.menu().actions(): #loop through the list of maps for the opened provider
if openLayersMap in map.text(): #if the desired map entry is found
map.trigger() #click the entry to load the map as a layer

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...