10

Using the CalculateField_management tool, one can specify the unit of measurement when calculating shape length:

#Calculate polyline lengths in miles
polylines = "C:\sampleShape.shp"
arcpy.CalculateField_management(polylines, "shapeLen", "!Shape.length@MILES!", "PYTHON_9.3")

I'd like to do the same thing within a cursor using the 'SHAPE@LENGTH' of each feature, with the length returned in a unit of my choosing:

#hypothetical example 1
with arcpy.da.UpdateCursor(polylines, field_names=["SHAPE@LENGTH.FEET", "shapeLen"]) as upCurs:
    for row in upCurs:
        row[1] = row[0]
        upCurs.updateRow(row)

Or possibly by using the (less efficient) @SHAPE geometry object?:

#hypothetical example 2
with arcpy.da.UpdateCursor(polylines, field_names=["@SHAPE", "shapeLen"]) as upCurs:
    for row in upCurs:
        row[1] = row[0].length@FEET
        upCurs.updateRow(row)

Is there some way to do this?

7

For now you'll need to use a workaround, the length will always be in the linear unit of the spatial reference of the geometry. Knowing the conversion factor for feet to meters and the metersPerUnit property should get you most of the way, or adding a field and using the field calculator's shape.length@feet like you mention before. Another option would be to specify the cursor's spatial reference as a geographic coordinate system (such as WGS84) and not a projected coordinate system. Then the Geometry.getLength() and geometry.getArea() methods will return numbers in meters, which you can again convert to feet pretty easily.

We just added an optional second argument to the Geometry.getLength/getArea methods at 10.2.1 to specify the units, so whenever it ships and whenever it gets to you you should have a direct way of doing it, but for now you should use another workaround.

6

With geometry objects, the getLength() method always returns a distance in meters, as seen here. That might be desirable if you only are converting to miles or feet, for instance. It would be relatively straightforward to convert from meters to any of the other linear distances.

If you want your length in decimal degrees, that becomes a bit trickier as the input must be in a Geographic Coordinate System (GCS). You might want to look into passing a SpatialReference object to your cursor, discussed here.

For instance, I have a polyline shapefile in NAD_1983_StatePlane_Louisiana_South_FIPS_1702_Feet, a Projected Coordinate System (PCS).

With this code, I can access the length of each object in decimal degrees:

spatref = arcpy.SpatialReference(4326) #EPSG code for WGS84
length = [row[0] for row in arcpy.da.SearchCursor("layer", "SHAPE@LENGTH", spatial_reference=spatref)]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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