TransWikia.com

Convert shapefile to geographic coordinates with og2ogr

Geographic Information Systems Asked on May 30, 2021

I’m trying to start plotting maps in python with matplotlib’s basemap, but every shapefile I’ve tried to far seems to have coordinates in metres instead of lat/lon, so I get the following error from readshapefile:

ValueError: shapefile must have lat/lon vertices - it looks like this one has vertices in map projection coordinates.

Here’s output from fiona about the shapefile I’m using:

shape = fiona.open('./data/ESRI/London_Ward.shp')
bounds = shape.bounds
print(shape.crs)

: {'proj': 'tmerc', 'lat_0': 49, 'lon_0': -2, 'k': 0.999601272, 'x_0': 400000, 'y_0': -100000, 'datum': 'OSGB36', 'units': 'm', 'no_defs': True}

print(bounds)
: (503568.2, 155850.8, 561957.5, 200933.9)

ogr2ogr is the only conversion tool I’ve managed to install so far, is it possible to use it to make the necessary conversion?

One Answer

Yes, it is. Use it like this from the command line (might be necessary to cd into the folder where ogr2ogr has been installed to):

ogr2ogr -t_srs EPSG:4326 -f "ESRI Shapefile" transformed.shp London_Ward.shp

If you want to run it from Python, you can use subprocess to set up the command and run it from the script, e.g. like this:

import subprocess as sub

input = r'./data/ESRI/London_Ward.shp'
output = r'./data/ESRI/London_Ward_WGS84.shp'
cmd = 'ogr2ogr -t_srs EPSG:4326 -f "ESRI Shapefile" {0} {1}'.format(output, input)
p = sub.Popen(cmd, stdout=sub.PIPE, stderr=sub.PIPE)
stdout, stderr = p.communicate()
if p.exitcode != 0:
    print stdout
    print stderr

Alternatively, pass all parts of the command as a list like this:

p = sub.Popen([ogr2ogr -t_srs EPSG:4326 -f "ESRI Shapefile", output, input], stdout=sub.PIPE, stderr=sub.PIPE)

In case you really want to stay within Python and don't use the command line, use the accepted answer from Python - OGR: Transform coordinates from meter to decimal degrees

Also have a look at the Documentation


EDIT: After working a bit more with subprocess, I would like to update the call to the following:

import subprocess as sub

input = r'./data/ESRI/London_Ward.shp'
output = r'./data/ESRI/London_Ward_WGS84.shp'
cmd = ['ogr2ogr', '-t_srs', 'EPSG:4326', '-f', '"ESRI Shapefile"', output, input]
sub.call(cmd)

subprocess seems to like lists better than pure string commands.

Correct answer by s6hebern on May 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP