Create Midpoints Along Lines with OGR
Today I found myself trying to create a ‘midpoint’ on a large shapefile line layer. QGIS doesn’t have a tool to do this, and because the layer was large, I really didn’t want to mess around converting file formats to stick it into a database. However, similar to my last post about Creating Points On A Surface Using OGR, I found a quick trick (via this question on gis.stackexchange.com) that also uses the awesome ‘-dialect’ switch in OGR. It works like this:
ogr2ogr OutputPoints.shp InputLines.shp -dialect sqlite -sql “SELECT AsText(Line_Interpolate_Point(InputLines.geometry, 0.5)),OTHER,FIELDS,CAN,GO,HERE from InputLines”
Simply replace “OutputPoints” with the desired output filename, and “InputLines” with the name of the line file you wish to create the midpoints from. You can change the “0.5″ to any number you wish – it represents how far along the line the point will fall, so if you want a midpoint, leave it at 0.5, but if you want the point 1/4 of the way along, change 0.5 to 0.25. If don’t specify fields where I have “OTHER,FIELDS,CAN,GO,HERE” you will get only a point file with no attributes. If you include other field names from InputLines.shp (comma separated) after the closing bracket, OGR will also return those attributes from InputLines.shp.
Here’s a quick visual:
Bonus assignment: rather than making an intermediate point layer, let’s just write the lat/lon of the midpoint directly to the attribute table:
ogr2ogr OutputLines.shp InputLines.shp -dialect sqlite -sql “SELECT *, X(Line_Interpolate_Point(InputLines.geometry, 0.5)) as X, Y(Line_Interpolate_Point(InputLines.geometry, 0.5)) as Y from InputLines”
Posted: January 27th, 2014 under GIS.