Take the 2-minute tour ×
Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. It's 100% free, no registration required.

I am new to the python console. How can I add a layer from the OpenLayers plugin from the python console? Thank you

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Renaud, there are a couple of ways to do this:

  1. Query QGIS's interface to find and trigger the appropriate menu action.
  2. Work directly with the already-loaded OpenLayers plugin.

Solution #1 is pretty straightforward. OpenLayers plugin offers a good solution to #2, which will help you understand working with other plugins as well. Here is how both are accomplished.

Trigger OpenLayers plugin menu action

layeract = 'Google Physical'
plugmenu = qgis.utils.iface.pluginMenu()
olmenu = False
for act in plugmenu.actions():
    if 'OpenLayers' in act.text():
        olmenu = act
        break
if olmenu:
    for act in olmenu.menu().actions():
        if layeract in act.text():
            act.trigger()

Work directly with OpenLayers plugin

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

This latter solution probably needs a little more explaining.

-> olplugin = qgis.utils.plugins['openlayers']

Get the OpenLayers plugin instance from qgis.utils's plugin registry.

-> ol_gphyslayertype = olplugin.olLayerTypeRegistry.getById(0)

Get the 'Google Physical' layer type object from OpenLayers's layer type registry. Open [path-to-user-plugins]/openlayers/openlayers_plugin.py and starting at line #111 you will see the order the layer types are assigned to the registry. They are given IDs starting with 0 (see rest of module for how that's done).

-> olplugin.addLayer(ol_gphyslayertype)

Loads the layer into QGIS's map canvas.

There may be other solutions as well, but those are the basics that I could find.

share|improve this answer
    
Thank you very much. I used the second option and it is working fine.python console seems very powerful ! –  Renaud Jun 11 '12 at 8:35
    
Is there an updated solution now that OpenLayers appear under the Web submenu instead of Plugins? –  Nyxynyx Oct 30 at 4:37

Since QGIS 2.4 Chugiak, the OpenLayers plugin has moved in the QGIS Gui to Web->OpenLayers plugin, hence the first method described above won't work anymore. I updated it to match the new menu structure, see my answer here.

Still, it would be interesting to know how to adapt the second method to QGIS 2.4 and above.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.