blake.terhune

Calc Latitude, Longitude Field

Discussion created by blake.terhune on Jun 8, 2015
Latest reply on Jun 17, 2015 by blake.terhune

After getting a lot of requests to get latitude and longitude coordinates for features, I created a generic script that creates two new fields in the existing feature feature class and and calcs the latitude and longitude of the feature's "true centroid." The only problem is that you would have to run this script any time a feature's geometry was changed. I did some searching for something that already existed and didn't find anything that was simple and generic enough, so please let me know if you can do it better.

 

import arcpy

fc = r"C:\temp\working.gdb\temp_fc"

# Define and create longitude/latitude fields
## Longitude is X, Latitude is Y
fieldsNew = ["GCS_WGS_1984_X", "GCS_WGS_1984_Y"]
fieldsExisting = {f.name: f.type for f in arcpy.ListFields(fc)}
for fNew in fieldsNew:
    # Add field if it doens't already exist
    if fNew not in fieldsExisting.keys():
        arcpy.AddField_management(
            fc,  ## in_table
            fNew,  ## field_name
            "DOUBLE",  ## field_type
        )
    # If data type of existing field is not a Double, throw Exception
    elif fieldsExisting[fNew] != "Double":
        raise Exception(
            "Existing {} field is type {}. Must be 'Double'".format(
                fNew, fieldsExisting[fNew]
            )
        )
# Update fields with GCS_WGS_1984 lat/long
print("Updating Field values")
fieldsNew.append("SHAPE@")
GCS_WGS_1984 = arcpy.SpatialReference(4326)
with arcpy.da.UpdateCursor(fc, fieldsNew, "", GCS_WGS_1984) as u_cursor:
    for row in u_cursor:
        point = row[2].trueCentroid
        row[0] = point.X
        row[1] = point.Y
        u_cursor.updateRow(row)

 

python snippets

Outcomes