Renaud, there are a couple of ways to do this:
- Query QGIS's interface to find and trigger the appropriate menu
action.
- 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.
If you are able to add a layer manually (Add Layer Dialog), you can get from it all the information needed to add it again via python.
Select the layer in the TOC
l = qgis.utils.iface.activeLayer()
p = l.dataProvider()
key = l.providerType()
uri = p.dataSourceUri()
QgsMapLayerRegistry.instance().addMapLayer( QgsVectorLayer( uri, 'layer', key ) )
In your case the key is 'spatialite'
Best Answer
Each data provider has its URI and its provider key. Once added via User Interface, it's easy to collect them and use them from the console.
Enter this statement in your python console, to collect the URI and key for all map layers:
to create a new map layer based on this information:
Vector Layer
Raster Layer
The key for MS SQL is 'mssql'
The uri follow the QgsDataSourceURI standard, which has an example in the PyQGIS cookbook chapter Loading Layers, Vector Layers. MS SQL works analogue to postgres.
The above example duplicates just one layer, but prints the necessary information to add each of them and gives an idea about the principle.