3

I want to add latitude and longitude column and their values in decimal degrees to my shapefile (fishnet). How to use ArcPy for that?

I have added lat and long using arcpy.AddGeometryAttributes_management but the unit I need is degree decimal and I got it in meters. My code is as below:

arcpy.AddGeometryAttributes_management("fish_lyr","CENTROID")

When specifying degree decimal:

arcpy.AddGeometryAttributes_management("fish_lyr","CENTROID","DEGREEDECIMALS")

it gives the following error:

ExecuteError: Failed to execute. Parameters are not valid.
ERROR 000800: The value is not a member of FEET_US | METERS | KILOMETERS | MILES_US | NAUTICAL_MILES | YARDS.
Failed to execute (AddGeometryAttributes).
0

2 Answers 2

5

You can use the da.UpdateCursor with the SHAPE@ token:

import arcpy

fc = r'C:\Test\Buildings.shp'
latfield = 'lat'
longfield = 'long'

with arcpy.da.UpdateCursor(fc,['SHAPE@',latfield,longfield]) as cursor:
    for row in cursor:
        a = arcpy.PointGeometry(row[0].centroid, arcpy.Describe(fc).spatialReference)
        b = a.projectAs(arcpy.SpatialReference(4326)).centroid
        row[1], row[2] = b.Y, b.X
        cursor.updateRow(row)
-1

In the case where the OP or a future reader can use geopandas instead of arcpy, you would do the following:

shp = 'C:/users/gis/data/fish.shp'
gdf = geopandas.read_file(shp)
(
    gdf.to_crs({'init': 'epsg:4326'}
        .assign(lon=lambda df: df['geometry'].centroid.x)
        .assign(lat=lambda df: df['geometry'].centroid.y)
        .to_crs(gdf.crs) 
        .to_file(shp)
)
3
  • @BERA I forgot to add the coordinate conversion. But I'm well aware that the OP wanted arcpy. If you read initial the premise of my answer, you'll see that I clearly acknowledged that. However, this could be a case of an X-Y problem for a different reader in the future, which case geopandas could make their life much easier.
    – Paul H
    Mar 19, 2019 at 14:47
  • In epsg:4326 the first axis (x) is lat, though
    – nmtoken
    Mar 19, 2019 at 16:39
  • @mmtoken, With geopandas/shapely, that order doesn't matter. Latitude, then longitude may be how we say these values, but latitude is still the y-direction. When I do this with a shape file near Portland, OR, USA, I get longitude values around -122.75 and latitude values around 45.57, which is what I expect.
    – Paul H
    Mar 19, 2019 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.