5

I have a layer with counties. I would like to import the bounding box of each county as a spatial bookmark and name it accordingly. Is this possible?

1
7

If you want to add details to the bookmarks such as the names or the project names then I think the only method is to access the SQLite database which stores these bookmarks. Using this great link as a guide, you could try running the following where you can define the field name, project name and the CRS:

import sqlite3
layer = iface.activeLayer()

dbPath = QgsApplication.qgisUserDbFilePath()
# if QGIS v3.14 or later, use following line instead:
# dbPath = QgsApplication.qgisUserDatabaseFilePath()

db = sqlite3.connect(dbPath)
cursor = db.cursor()

# Define the following information
fieldName = 'Name'
projectName = 'Scotland'
SRID = '27700'

for feat in layer.getFeatures():
    rect = feat.geometry().boundingBox()
    cursor.execute("""INSERT INTO tbl_bookmarks(bookmark_id, name, project_name,xmin, ymin, xmax, ymax,projection_srid)
        VALUES(NULL, '""" + feat[fieldName] + """', '""" + projectName + """', """ + 
        '%f,%f,%f,%f'%(rect.xMinimum(),rect.yMinimum(),rect.xMaximum(),rect.yMaximum()) + """, """ + 
        SRID + """)""")

db.commit()

Example:

Scotland bookmarks


Notes:

1. The bookmarks panel is not immediately updated, you will need to add a new bookmark to see the panel refreshed.

2. I had an issue with the Projection CRS. My layer's CRS was set at EPSG:27700 but setting the projection to the same CRS resulted in a transformation error. I had to set the projection to EPSG:4326 to rectify it (I also had OTF disabled).

6
  • Great. That works already! Only one detail is missing: The bookmarks do not have a name yet. – coding_bird Jun 16 '17 at 14:15
  • 2
    @coding_bird - Yeah, I don't think there is a direct method using the API. You may have to access the SQLite database (which QGIS stores the bookmarks in) and add it from there (as described in this link). I'm guessing you would want to name them after the name of each county (i.e. there's a field in your layer containing the names)? – Joseph Jun 16 '17 at 14:22
  • 1
    @coding_bird - Edited my post to include a possible method :) – Joseph Jun 16 '17 at 15:16
  • 1
    Thanks. Very good :-D I removed the first part of your answer, because the "new" part explains everthing much better. I hope you agree. By the way: This would be a good idea for a QGIS plugin, right? :-) – coding_bird Jun 16 '17 at 15:27
  • @coding_bird - Most welcome! And yes, I also agree with the edit so thanks for that.. I don't think there is an existing plugin which does this (or atleast I couldn't find one) so yeah, I suppose it would be a good idea to make it into a plugin :) – Joseph Jun 19 '17 at 8:11

Your Answer

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

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