Monday, November 13, 2017

QGIS: Adding Bounding Box Ordinates as Shapefile Attributes

I mentioned last week, that for the purpose of zooming to a hydrology region when it's selected, we added some attributes to a CSV of metadata, which we were already loading for other UI and statistical purposes.

These attributes were called bbox_s, bbox_w, bbox_n, and bbox_e and are simply floats in WGS84 lat-long. But I thought I'd share how I generated 4 fields representing the bounding box, for these regions (and then later for a few hundred individual watersheds) quickly and easily.

To back up a bit:

  • The CSV was generated from the DBF component of that hydrology regions shapefile. Excel can load up the DBF just fine, then you use Save As and export as a CSV. Easy.
  • The shapefile has attributes of statistics which were generated by other means. The stats were miles of river, number of gauges, that sort of deal where GIS was the answer.
  • The only missing attributes now are the bounding box fields, preferably 4 floats in WGS84 lat-long.
This was done with QGIS's Field Calculator, using built-in functionality. The Field Calculator supports geometry operations including xmin and transform. So it's simple:

Take note of what SRS you are using, particularly its EPSG code.

Create a new field called bbox_s of type float. Don't forget to give it a Precision for after the decimal place! If you leave Precision at 0, the fields will still calculate but will then be truncated to whole numbers after you save.

Populate it with this formula, being sure to replace the first SRS with your dataset's own SRS:


y_min(transform($geometry, 'EPSG:3310', 'EPSG:4326'))

And there you are! You now have an attribute with the southern ordinate of the bbox. Repeat this 3 more times:

bbox_w
x_min(transform($geometry, 'EPSG:3310', 'EPSG:4326'))
 
bbox_e
x_max(transform($geometry, 'EPSG:3310', 'EPSG:4326'))
 
bbox_s
y_min(transform($geometry, 'EPSG:3310', 'EPSG:4326'))
bbox_n
y_max(transform($geometry, 'EPSG:3310', 'EPSG:4326'))

Save your edits, and you're nearly done. Load up the DBF in Excel, maybe tidy up some other fields and their formatting, and export as CSV.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.