Creating a map bookmark

Map bookmarks allow you to save a location on a map in QGIS, so you can quickly jump to the points you need to view repeatedly without manually panning and zooming the map. PyQGIS does not contain API commands to read, write, and zoom to bookmarks. Fortunately, QGIS stores the bookmarks in an SQLite database. Python has a built-in SQLite library that we can use to manipulate bookmarks using the database API.

Getting ready

You can download a census tract polygon shapefile to use with this recipe from https://geospatialpython.googlecode.com/files/GIS_CensusTract.zip.

Extract it to your qgis_data directory. We are going to create a bookmark that uses an area of interest within this shapefile, so you can manually load the bookmark in order to test it out.

How to do it...

We will access the QGIS configuration variables to get the path of the user database, which stores the bookmarks. Then, we'll connect to this database and execute a SQL query that inserts a bookmark. Finally, we'll commit the changes to the database, as follows:

  1. First, using the QGIS PythonConsole, we must import Python's built-in SQLite library:
    import sqlite3
    
  2. Next, get the path to the database:
    dbPath = QgsApplication.qgisUserDbFilePath()
    
  3. Now, we connect to the database:
    db = sqlite3.connect(dbPath)
    
  4. Then, we need a database cursor to manipulate the database:
    cursor = db.cursor()
    
  5. Now, we can execute the SQL query, which is a string. In the VALUES portion of the query, we will leave the bookmark ID as NULL but give it a name, then we leave the project name NULL and set the extents, as follows:
    cursor.execute("""INSERT INTO tbl_bookmarks(
      bookmark_id, name, project_name,
      xmin, ymin, xmax, ymax, 
      projection_srid)
      VALUES(NULL, "BSL", NULL,
        -89.51715550010032,
        30.233838337125075,
        -89.27257255649518,
        30.381717490617945,
        4269)""")
    
  6. Then, we commit the changes:
    db.commit()
    
  7. To test the map bookmark, load the census tract layer onto the map by dragging and dropping it from your filesystem into QGIS.
  8. Next, click on the View menu in QGIS and select ShowBookmarks.
  9. Then, select the BSL bookmark and click on the ZoomTo button.
  10. Verify that the map snapped to an area of interest close to the polygons, with OBJECTIDs from 4625 to 4627.

How it works...

Even when QGIS doesn't provide a high-level API, you can almost always use Python to dig deeper and access the information you want. QGIS is built on open source software, therefore no part of the program is truly off-limits.

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

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