Friday, November 12, 2010

Python Tip: Coordinate Clean Up

If you create point features from coordinates stored in flat tables you probably find cases where the longitude and latitude are reversed or a negative sign is missing.  This happens frequently if the source of the data is from a non-GIS user.  What can make fixing these mistakes more difficult is if the errors are not consistent through out the table.  The following Python example will switch the longitude and latitude if necessary and add negative signs if missing.  Note: This code is only useful if all the points are with in the same hemisphere.  If the points are located across the globe, a solution to this problem is much more difficult.

First, import the modules and create the geoprocessor:

import sys, string, os, arcgisscripting

gp = arcgisscripting.create()
gp.OverWriteOutput = 1

Next, create an Update Cursor:

rows = gp.UpdateCursor(r"C:\Project\sample.gdb\table")
row = rows.Next()

Now you need to loop through each row in the table and get the longitude and latitude values.  Note that the XCOORDINATE and YCOORDINATE are the name of the field ins the table:

while row:
     xCoord = row.XCOORDINATE
     yCoord = row.YCOORDINATE

We will need to switch the longitude and latitude if they are reversed.  We do this by checking to see if the longitude is within a valid range.  In this all points should fall with 30 to 50 degrees West Longitude.  If they do not, we assume that they are switched and switch them:

      if xCoord > 30 and xCoord < 50:
          row.XCOORDINATE = yCoord
          row.YCOORDINATE = xCoord
          xCoord = yCoord

We use simpler logic to check for a missing negative sign.  In this case the longitude should be negative so we check.  If it is not, we make it negative:

     if xCoord > 50:
          xCoord = xCoord - (xCoord * 2)
          row.XCOORDINATE = xCoord

Now that the changes have been made if necessary we update the row and move to the next row:

     rows.UpdateRow(row)
     row = rows.Next()

Finally, delete the cursor:

del row
del rows

As you can see the values will change depending on the location of your points, but this general logic should solve most of your problems.  And like all examples, there are several ways to do most of these steps.