3

I'm putting together a plugin for QGIS. The user inputs a county and a coordinate pair. The plugin then adds in the county data and zooms to the given coordinates.

The problem is that there are multiple counties with the same name, when zoomed into the coord pair, the county data may be visible but not active because there are multiple layers with the same name added.

I need a way to activate the layer that is in view/visible/can-be-seen-at-the current-position in canvas. I've tried:

import qgis
import qgis.utils
canvas = qgis.utils.iface.mapCanvas()

layers = qgis.utils.iface.legendInterface().layers()
i = qgis.utils.iface
legend = i.legendInterface()

#iter through the legend layers
for layer in layers:
#if the name of the layer is the same as the what the user input
if layer.name().lower() == county.lower():
    #and you can see it in the canvas/in the extent/if youre looking at it  
    if canvas.extent() == layer.extent():
        #make the layer active so i can select, or identify things
        iface.setActiveLayer(layer)

legend.isLayerVisible(layer) is not what im looking for, it toggles layers, the data is already visible, I need the layer in my current position active.

  • I think, instead of if canvas.extent() == layer.extent() you should use if canvas.extent().contains(layer.extent()) to test if layer lies in current canvas extent. – Henhuy Jun 13 '16 at 7:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.