Reprojecting in Python

My previous post declared my plugging my nose and jumping into Python GIS stuff. Advice and info from Sean have been valuable in getting familiar with things, though I’ll be the first to admit I’m still green (writing Python like a Perl / C hack 🙂 ).

So here’s one of my first attempts at solving a real world problem: reprojecting a bunch of points from a CSV file:

import sys
import mapscript

if (len(sys.argv) == 1):
	print sys.argv[0] + " <csvfile>"
	projInObj  = mapscript.projectionObj("init=epsg:32619")
	projOutObj = mapscript.projectionObj("init=epsg:4326")
	print "id,geom,zone"
	f = open(sys.argv[1], 'r')
	for line in f:
		s = line.strip()
		k = s.split(",")
		wkt = "POINT(" + k[1] + " " + k[2] + ")"
		shape = mapscript.shapeObj.fromWKT(wkt) # man, I love WKT!!
		shape.project(projInObj, projOutObj)
		print k[0] + "," + shape.toWKT() + "," + k[3]

And that’s it! So now you can take the CSV output with the geometry encoded as WKT and hook it up to MapServer with some simple OGR OVF syntax in your mapfile:

<OGRVRTLayer name='nb'>
<GeometryField encoding='WKT' field='geom'/>

Mind you, you might question why to reproject when MapServer can do this for you, but I digress. There’s probably more eloquent ways to do this than what’s been done above via mapscript, eh?

2 Comments so far »

  1. Justin Bronn said,

    Wrote on July 14, 2007 @ 20:18:36

    Mozilla Firefox Windows XP

    You may also use GeoDjango to accomplish this task. Further, Python has a built in CSV module that makes life easier — check out my example here:

    Posted from United States United States
    Mozilla Firefox Windows XP
  2. Sean Gillies said,

    Wrote on July 14, 2007 @ 21:49:07

    Mozilla Firefox Ubuntu Linux

    Yes, there is. Use pyproj ( to transform coordinate lists (or numpy arrays) in one try. No need to fool with WKT or creating shapeObjs.

    Posted from United States United States
    Mozilla Firefox Ubuntu Linux

Comment RSS · TrackBack URI

Leave a Comment

Name: (Required)

E-mail: (Required)



Modified: 14 July 2007 18:41:57 EST