Navigating to a map bookmark

Map bookmarks store important locations on a map, so you can quickly find them later. You can programmatically navigate to bookmarks using the Python sqlite3 library in order to access the bookmarks database table in the QGIS user database and then use the PyQGIS canvas API.

Getting ready

We will use a census tract layer to test out the bookmark navigation. You can download the zipped shapefile from https://geospatialpython.googlecode.com/files/GIS_CensusTract.zip.

Manually load this layer into QGIS after extracting it from the ZIP file. Also, make sure that you have completed the previous recipe, Creating a map bookmark. You will need a bookmark named BSL for an area of interest in this shapefile.

How to do it...

We will retrieve a bookmark from the QGIS user database and then set the map's extents to this bookmark. To do this, perform the following steps:

  1. First, import the Python sqlite3 library:
    import sqlite3
    
  2. Next, get the location of the user database from the QGIS data:
    dbPath = QgsApplication.qgisUserDbFilePath()
    
  3. Now, we connect to the database:
    db = sqlite3.connect(dbPath)
    
  4. Then, we need a database cursor to run queries:
    cursor = db.cursor()
    
  5. Now, we can get the bookmark information for the bookmark named BSL:
    cursor.execute("""SELECT * FROM tbl_bookmarks WHERE name='BSL'""")
    
  6. Now, we'll get the complete results from the query:
    row = cursor.fetchone()
    
  7. Then, we split the values of the result into multiple variables:
    id,mark_name,project,xmin,ymin,xmax,ymax,srid = row
    
  8. Now, we can use the bookmark to create a QGIS extent rectangle:
    rect = QgsRectangle(xmin, ymin, xmax, ymax)
    
  9. Next, we reference the map canvas:
    canvas = qgis.utils.iface.mapCanvas()
    
  10. Finally, we set the extent of the canvas to the rectangle and then refresh the canvas:
    canvas.setExtent(rect)
    canvas.refresh()
    

How it works...

Reading and writing bookmarks with SQLite is straightforward even though its not a part of the main PyQGIS API. Notice that bookmarks have a placeholder for a project name, which you can use to filter bookmarks by project if needed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset