Creating Points On a Surface using OGR
If you’ve ever had to create a point on a polygon surface, you fairly quickly realize that there’s a lack of easy tools that will perform this task. Almost every desktop GIS package will create a ‘centroid,’ but that doesn’t work when you need to find a point that’s guaranteed to fall on the surface of your polygon. Below is an example of two polygons that will work fine with a ‘centroid’ tool, and two that will cause the resulting point to fall off the surface of the polygon:
Running the QGIS “Polygon Centroids” tool on these polygons gives the following results:
Of course, many of the more advanced GIS packages (PostGIS, SpatiaLite, etc.) have a tool for this exact purpose. However, the problem is that often those tools are overkill, or require you to convert your data format in order to use their nifty spatial functions. What a pain!
However, there’s an easy solution, and once again, it involves the heavy-hitter OGR , which never ceases to amaze me with its functionality. One simple command will create points forced onto the polygon surface, using the smarts of SpatiaLite, but not requiring you to convert formats or load anything into a database. Here’s all you need to run, from the command line (I suggest installing OGR via OSGeo4W if you’re on Windows):
ogr2ogr OutputPoints.shp InputPolygons.shp -dialect sqlite -sql “SELECT ST_PointOnSurface(geometry) from InputPolygons”
That’s it! The result is a point for each polygon, with it ‘forced’ onto the surface.
Cool eh? Observant readers will notice that all the OGR command is doing is actually changing it’s ‘dialect’ to sqlite, which allows you to pass in any SpatiaLite query. This of course opens up many of the other awesome tools available to you, right from the command line, with any file type. Perhaps I’ll post some other neat examples soon; stay tuned!
Posted: November 9th, 2013 under GIS.