1

I am trying to join two feature classes together and also keep the spatial geometry of the join features. I want to keep the target and output geometry the same but also have a field like JoinSHAPE where I can access the geometry of the feature that it was joined with.

I have tried to add a field mapping for the join feature but an error occurs.

RuntimeError: FieldMap: Error in adding input field to field map

when I run the code below.

import arcpy

target = arcpy.GetParameter(0)
join_features = arcpy.GetParameter(1)
output =  r"S:\GIS TOOLS\Workbench.gdb\asdf"


fieldmappings = arcpy.FieldMappings()
fieldmappings.addTable(target)
fieldmappings.addTable(join_features)

shape = arcpy.FieldMap()
shape.addInputField(join_features, "SHAPE@")
fieldmappings.addFieldMap(shape)

arcpy.SpatialJoin_analysis(target, join_features, output, "#", "#", fieldmappings)
3

You can't join a geometry field. However, a nifty work-around could be populating a field with the geometry in WKT or JSON format:

json_field = 'JSON'
arcpy.AddField_management(join_features, json_field, 'TEXT', field_length=5000) # The length depends on how complex your geometries are.
with arcpy.da.UpdateCursor(join_features, ['SHAPE@JSON', json_field]) as cur:
    for row in cur:
        row[-1] = row[0]
        cur.updateRow(row)

...
shape.addInputField(join_features, json_field)
...

See here to learn about shape tokens.

Later on, when you want to read the joined geometry, you can use the AsShape tool:

with arcpy.da.SearchCursor(target, json_field) as cur:
    for row in cur:
        geometry = arcpy.AsShape(row[0], True)

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.