Hi everyone. I am attempting to create a script tool that assigns a coordinate system across all maps within a Pro project. The purpose of this is to avoid having to assign each projection manually after creating a new map.
I first wrote out the code with hard-coded variables, which runs perfectly:
import arcpy
# Reference the current project
aprx = arcpy.mp.ArcGISProject("CURRENT")
# Define the target coordinate system (use a WKID or Name)
# Example: 4326 is WGS 1984
new_sr = arcpy.SpatialReference(2285)
# Loop through all maps in the project
for map_obj in aprx.listMaps():
# Assign the new spatial reference to the map
map_obj.spatialReference = new_sr
print(f"Updated projection for map: {map_obj.name}")
# Save the project to commit changes
aprx.save()
This is the altered code I created to insert inside the Script tool:
import arcpy
arcpy.env.overwriteOutput = True
try:
aprx = arcpy.mp.ArcGISProject("CURRENT")
# Get the SpatialReference object directly from the tool parameter
spatial_ref = arcpy.GetParameter(0)
# Iterate through maps
for map_object in aprx.listMaps():
map_object.spatialReference = spatial_ref
arcpy.AddMessage(f"Updated projection for: {map_object.name}")
# Save once after all updates are complete
aprx.save()
arcpy.AddMessage("All maps updated and project saved.")
except Exception as e:
arcpy.AddError(f"Error assigning coordinate systems: {str(e)}")
When I run the script, I am prompted to select a coordinate system, which is exactly what I want. However, when I run the script, it fails with the error message Error assigning coordinate systems: SpatialReference: Input value is not valid.
These are my parameters within the script.
I know that it's something related to the coordinate system input parameter, I just can't figure out what. FYI I am a beginner to coding/making script tools so please give me advice in layman's terms 🙂 TIA!!
Solved! Go to Solution.
There is a "Spatial Reference" under the Data Type drop down... did you try it
There is a "Spatial Reference" under the Data Type drop down... did you try it
Hi, that worked! I knew it was an easy fix, thanks for pointing me in the right direction 🙂