ArcPy Distance – Calculate Distance Between Two Geometries Using ArcPy

arcgis-proarcpydistance

I have managed to write the following code where I am looping through features of "Source Layer", getting its primary and foreign key. Then selecting that feature using primary key from "Source Layer" and selecting the feature using foreign key in "Target Layer".

Now I want to calculate the distance between these two geometries regardless of their type and print.

import arcpy
Source_Layer = "Data1\\Asset_2"
Target_Layer = "FL1\\Road_FL"
with arcpy.da.SearchCursor(SL,['Asset_ID','FL_ID']) as cur:
   for rows in cur:       
    AssetID = rows[0]
    FLID = rows[1]        
    where_clause = "Asset_ID = {}".format(rows[0])
    where_clause2 = "ID = '" +  str(FLID)+ "'"
    Source_Feature = arcpy.management.SelectLayerByAttribute(SL,'New_Selection', where_clause)
    Target_Feature = arcpy.management.SelectLayerByAttribute(TL,'New_Selection', where_clause2)
    # Distance = (????????????) # calculate distance here
    print (AssetID, FLID, Distance)

Best Answer

You can use the geometry access token to get the geometry of both features and use distanceTo method to get their didtance

import arcpy
SL = "Data1\\Asset_2"
TL = "FL1\\Road_FL"
with arcpy.da.SearchCursor(SL,['Asset_ID','FL_ID', 'SHAPE@']) as scur:
   for rows in scur: 
    geom1 = row[2]      
    AssetID = rows[0]
    FLID = rows[1]        
    where_clause = "ID = '" +  str(FLID)+ "'"
    with arcpy.da.SearchCursor(TL,['ID', 'SHAPE@'], where_clause) as tcur:
        feat2 = tcur.next()
        geom2 = feat2[1]
        Distance = geom1.distanceTo(geom2) # calculate distance here
        print (AssetID, FLID, Distance)