Available with Standard or Advanced license.
Available with Production Mapping license.
Summary
The Grid object provides access to grid properties for a grids and graticules layer. A reference to the Grid object is often used as an argument for functions to access grid properties.
Discussion
The Grid object provides access to important properties of a grid, which is created using the Make Grids And Graticules Layer geoprocessing tool or the Grids and Graticules Designer. The ListGrids function can be used to return a list of the Grid objects in a feature dataset. An in-memory grid object can be created from a Grid Template(XML File) by using Grid(<grid_xml_path>).
Properties
Property | Explanation | Data Type |
baseSpatialReference (Read Only) | Returns the base spatial reference of the grid's primary coordinate system. | SpatialReference |
layer (Read Only) | Returns the group layer created from the Grid object. The group layer contains all grid subcomponents as sublayers. This is the same as the output group layer from the Make Grids And Graticules Layer geoprocessing tool. | Layer |
name (Read and Write) | Provides the ability to get or set the name of the Grid object. The name for the cartographic grid may not be the name of the layer. The name allows for distinction between grids stored in the same feature dataset and set of feature classes. | String |
scale (Read and Write) | Provides the ability to get or set the reference scale of the Grid object. | Double |
type (Read and Write) | Provides the ability to get or set the type associated with the Grid object. All grids of the same type will have the same appearance. Type defines a style of grid, map product, or series. | String |
Method Overview
Method | Explanation |
updateDataFrameProperties (data_frame, {area_of_interest}) | Updates the coordinate system, rotation, scale, data frame size, and shape based on the properties and values stored in the Grid object. |
calculateExtent (data_frame_width, data_frame_height, input_point_geometry, scale, {page_units}) | Calculates the extent/AOI of a map based on the map data frame size, scale, and properties from the current Grid object. |
calculateDataFrameSize (area_of_interest, scale, {output_page_units}) | Calculates the data frame size based on an AOI and scale. |
calculateScale (data_frame_width, data_frame_height, area_of_interest, {page_units}) | Calculates the scale of a map based on the map data frame size, page units, area of interest, and properties from the current Grid object. |
Methods
updateDataFrameProperties (data_frame, {area_of_interest})
Parameter | Explanation | Data Type |
data_frame | A reference to a DataFrame object within a map document. | DataFrame |
area_of_interest | A geometry that represents the area of the map. | Geometry |
This method provides functionality that is equivalent to the Grid Layout tool. It is used to ensure that the key cartographic data frame properties match the grid, thus enforcing the map display to show shapes, sizes, and measurements as intended based on the grid design. It projects the data frame to the grid's primary coordinate system, changes data frame scale to match the grid's scale, changes data frame size to grid's extent at specified scale, and rotates data frame to grid's specified rotation angle. If the grid is created from an XML file, the optional area_of_interest parameter needs to be defined.
The following example updates the .mxd file's data frame properties based on those in the Rotation Scale GCS grid object.
import arcpy
import arcpyproduction
# Check out Production Mapping extension
arcpy.CheckOutExtension("Foundation")
# Set the grid workspace and name
gridWorkspace = r'C:\Project\Grids\GridsUpdateDF.gdb\WGS84'
gridName = "RotationScaleGCS"
# Define the map document, data frame, and layout view
mxd = arcpy.mapping.MapDocument(r"C:\Project\Grids\GridsUpdateDFTest.mxd")
active_df = mxd.activeDataFrame
mxd.activeView = "PAGE_LAYOUT"
# Update data frame using the properties of the RotationScaleGCS grid
# and save results in a new .mxd
Rotationgrids = arcpyproduction.mapping.ListGrids(gridWorkspace, gridName)
if Rotationgrids[0].name == gridName:
Rotationgrids[0].updateDataFrameProperties(active_df)
mxd.saveACopy(r"C:\Project\Grids\UpdateResults.mxd")
else:
print "Error Obtaining Grid "+ gridName
# Check in extension
arcpy.CheckInExtension("Foundation")
The following example updates the .mxd file's data frame properties based on an XML grid and the defined AOI.
import arcpy
import arcpyproduction
# Check out Production Mapping extension
arcpy.CheckOutExtension("Foundation")
#Get the grid object using its XML path
ArcDir = arcpy.GetInstallInfo()['InstallDir']
grid = arcpyproduction.mapping.Grid(ArcDir + r"\GridTemplates\GridTemplates\Topo_50K_WGS84.xml")
#Define the map document, dataframe to update, and set it to Layout View
mxd_path = r"C:\Project\TopoMap.mxd"
mxd = arcpy.mapping.MapDocument(mxd_path)
df = mxd.activeDataFrame
mxd.activeView = "PAGE_LAYOUT"
# Get an Area of Interest feature for which that grid can be applied
feature_class = r'C:\Project\AOI.gdb\TLM50'
query_exp = "MSNAME = 'R712X44584'"
with arcpy.da.SearchCursor(feature_class,["MSNAME","SHAPE@"],query_exp) as cur:
for row in cur:
name = row[0]
geom = row[1]
# Update the dataframe properties using the grid and save as a new mxd
grid.updateDataFrameProperties(df,geom)
mxd.saveACopy(r"C:\Project\Update_"+name+"_Results.mxd")
# Check in extension
arcpy.CheckInExtension("Foundation")
calculateExtent (data_frame_width, data_frame_height, input_point_geometry, scale, {page_units})
Parameter | Explanation | Data Type |
data_frame_width | The width of the data frame in page units. | Double |
data_frame_height | The height of the data frame in page units. | Double |
input_point_geometry | A Geometry object referencing a centroid of a map. | Geometry |
scale | The map scale to be used for calculating the extent. | Double |
page_units | Specifies which ArcGIS-supported page units are being used for the data_frame_height and data_frame_width parameters. The default is INCHES. The options are the following:
(The default value is INCHES) | String |
Return Value
Data Type | Explanation |
Geometry | A polygon geometry (AOI) that represents the map extent. |
All maps display on a flat surface (page or screen), showing some geographic extent at a defined scale. However, only a specific amount of ground area can be seen on a flat surface at a specific scale.
There are a number of factors used in calculating the size of maps:
- Geographic extent—The area on the ground that will be displayed in a map.
- Flat viewing surface’s extent—The size of the window (or data frame) through which the area on the ground is displayed.
- Map scale—The ratio of a distance on the map to the corresponding distance on the ground.
Complicating this calculation is the curvature of the earth's surface; the coordinate system of the flat surface as well as the geographic extent’s specific latitude and longitude must also be factored into the calculation.
The calculateExtent method is used to calculate the geographic extent of a map by providing a data frame’s size and scale. This method also uses the latitude and longitude of the provided input point geometry with the coordinate system and data frame rotation information assigned to the grid object being used.
The following example creates an extent based on the specification in the Calibrated grid template in GridTemplates and the defined input parameters.
import arcpy
import arcpyproduction
#Create a point with known spatial reference e.g. WGS_1984_Web_Mercator_Auxillary_Sphere
sr = arcpy.SpatialReference(3857)
newPoint = arcpy.Point(-13046304, 4036487)
pointGeom = arcpy.PointGeometry(newPoint,sr)
#Create a reference to a grid that will be used to calculate the extent
#This sample uses the Calibrated grid template in GridTemplates
grid_template = arcpy.GetInstallInfo()['InstallDir']+r"\GridTemplates\Calibrated_1500K_to_2250K_WGS84.xml"
grid = arcpyproduction.mapping.Grid(grid_template)
#Define the input dataframe size and scale for which the new extent will be calculated
dataframe_width = 8
dataframe_height = 11
scale = 50000
#Create a new extent based on the defined input parameters
newExtent = grid.calculateExtent(dataframe_width,dataframe_height,pointGeom,scale)
#Create a copy of the new extent by using the CopyFeatures tool
arcpy.CopyFeatures_management(newExtent, "C:/geometry/NewExtent.shp")
calculateDataFrameSize (area_of_interest, scale, {output_page_units})
Parameter | Explanation | Data Type |
area_of_interest | A polygon geometry that represents the area of the map. | Geometry |
scale | The map scale to be used for calculating the extent. | Double |
output_page_units |
Specifies which ArcGIS supported page units the output data frame size should be. The default is inches. (The default value is Inches) | String |
Return Value
Data Type | Explanation |
Dictionary | A dictionary in the format {'width': 8, 'height': 11} that represents the map extent. |
The calculateDataFrameSize method is similar to the updateDataFrame method. The updateDataFrame takes a data frame object as input and then updates its properties. However, CalculateDataFrameSize is a lighter weight method that only returns the values of the final data frame size. This method is more useful for tasks where only a size is needed. For example, you can use the CalculateDataFrameSize method to understand and visualize how a data frame might change if updateDataFrame was applied. You can also use this method when you don't want to change the data frame properties.
CalculateDataFrameSize example 1
This sample calculates a new data frame size in centimeters based on the extent of a polygon.
import arcpy
import arcpyproduction
#Create a polygon with known spatial extent
sr = arcpy.SpatialReference(4326)
feature_info = [[[-118.98788717299999,33.364948072000061],
[-119.13720283799995,33.364952839000068],
[-119.13732730399994,33.510033881000027],
[-118.98776270299999,33.510038646000055],
[-118.98788717299999,33.364948072000061]]]
for feature in feature_info:
# Create a Polygon object based on the array of points
# Append to the list of Polygon objects
newpoly = arcpy.Polygon(arcpy.Array([arcpy.Point(*coords) for coords in feature]),sr)
#Create a reference to a grid that will be used to calculate the dataframe size
grid_template = arcpy.GetInstallInfo()['InstallDir']+r"\GridTemplates\Topo_50K_WGS84.xml"
grid = arcpyproduction.mapping.Grid(grid_template)
#Determine the dataframe size
newDFSize = grid.calculateDataFrameSize(newpoly, 50000, 'CENTIMETERS')
print ("The Calculated Dataframe size is: \nwidth : {0} \nheight : {1} \nThe output units are in {2}"
.format(str(newDFSize['width']),str(newDFSize['height']),newDFSize['units']))
CalculateDataFrameSize example 2
This sample calculates a new data frame and uses the new dimensions to determine the correct product MXD to use.
import os
import arcpy
import arcpyproduction
#Create a polygon with known spatial extent
sr = arcpy.SpatialReference(4326)
feature_info = [[[-118.98788717299999,33.364948072000061],
[-119.13720283799995,33.364952839000068],
[-119.13732730399994,33.510033881000027],
[-118.98776270299999,33.510038646000055],
[-118.98788717299999,33.364948072000061]]]
for feature in feature_info:
# Create a Polygon object based on the array of points
# Append to the list of Polygon objects
newpoly = arcpy.Polygon(arcpy.Array([arcpy.Point(*coords) for coords in feature]),sr)
#Create a reference to a grid that will be used to calculate the dataframe size
grid_template = arcpy.GetInstallInfo()['InstallDir']+r"\GridTemplates\Topo_50K_WGS84.xml"
grid = arcpyproduction.mapping.Grid(grid_template)
#Get the dataframe size
newDF = grid.calculateDataFrameSize(newpoly, 50000)
#Get a list of MXDs from a folder and its respective page dimensions
mxdPath = r"C:\Project"
mxd_pagesize_list = []
for f in os.listdir(mxdPath):
if os.path.isfile(os.path.join(mxdPath,f)):
if len(f.split(".mxd")) > 1:
mxd = arcpy.mapping.MapDocument(os.path.join(mxdPath,f))
m = [f, mxd.pageSize.width, mxd.pageSize.height]
mxd_pagesize_list.append(m)
#Determine the appropriate MXD to use
final_mxd = ''
x = []
for eachItem in mxd_pagesize_list:
if [eachItem[1],eachItem[2]] < x or len(x) == 0:
if newDF['width'] < eachItem[1] and newDF['height'] < eachItem[2]:
final_mxd = eachItem[0]
x = [eachItem[1],eachItem[2]]
print "The mxd to use is "+final_mxd
calculateScale (data_frame_width, data_frame_height, area_of_interest, {page_units})
Parameter | Explanation | Data Type |
data_frame_width | The width of the data frame in page units. | Double |
data_frame_height | The height of the data frame in page units. | Double |
area_of_interest | A polygon geometry that represents the area of the map. | Geometry |
page_units | Specifies which ArcGIS-supported page units are being used for the data_frame_height and data_frame_width parameters. The default is INCHES. The options are the following:
(The default value is INCHES) | String |
Return Value
Data Type | Explanation |
Double | The calculated map scale. |
The calculateScale method is similar to the calculateDataFrameSize. It is also a lightweight method that returns only the scale value based on the provided area of interest of the map and data frame size. This method is useful for tasks where only a scale should be calculated. This is helpful to understand and visualize what the map scale should be set to for displaying a specific geographic extent (area of interest) using a data frame of a specific page size. For example, you can calculate the scale that would be set if the grid object method of updateDataFrameProperties was applied.
The following example calculates the scale based on input parameters.
#Import module and checkout the extension
import arcpyproduction
arcpy.CheckOutExtension("foundation")
#Create a reference to a grid that will be used to calculate the dataframe size
grid_template = arcpy.GetInstallInfo()['InstallDir']+r"\GridTemplates\Topo_50K_WGS84.xml"
grid = arcpyproduction.mapping.Grid(grid_template)
#Get the AOI geometry
feature_class = r"C:\MapIndex.gdb\Topo50K"
query_exp = "MSNAME = 'V734X53601'"
with arcpy.da.SearchCursor(feature_class,["MSNAME","SHAPE@"],query_exp) as cur:
for row in cur:
area_of_interest = row[1]
#Identify the map dimensions
df_width = 210
df_height= 297
units = "MILLIMETERS"
#Calculate scale
scale = grid.calculateScale(df_width, df_height, area_of_interest, units)
print scale
arcpy.CheckInExtension("foundation")
Code sample
Grid example 1
The following script will read the name and type properties of grids in an existing workspace and delete the grids from the workspace using the properties as parameters in the Delete Grids and Graticules geoprocessing tool.
import arcpy
import arcpyproduction
# Check out Production Mapping extension
arcpy.CheckOutExtension('foundation')
# Set the grid workspace
grid_dataset = r"C:\Project\Grids.gdb\WGS84"
# Get the list of grids in the workspace
lstGrids = arcpyproduction.mapping.ListGrids(grid_dataset)
# Loop through the list of grids and delete each grid
# Delete Grids And Graticules accepts grid name and type as a second parameter
# The second parameter format is <grid name> (<grid type>)
for grid in lstGrids:
grid_name = grid.name
grid_type = grid.type
arcpy.DeleteGridsAndGraticules_cartography(grid_dataset, grid_name + ' (' + grid.type + ')')
# Check in extension
arcpy.CheckInExtension('foundation')
Grid example 2
This sample creates the grid object from a grid XML file and checks the type and scale.
import arcpy
import arcpyproduction
# Check out Production Mapping extension
arcpy.CheckOutExtension("foundation")
# Create grid object from a XML file and check type and scale
ArcDir = arcpy.GetInstallInfo()['InstallDir']
gridobj = arcpyproduction.mapping.Grid(ArcDir + r"\GridTemplates\Calibrated_1500K_to_2250K_WGS84.xml")
print "Grid Type = " + str(gridobj.type) + " Grid Scale = " + str(gridobj.scale)
# Check in extension
arcpy.CheckInExtension("foundation")
Grid example 3
This sample script uses the base spatial reference property of a grid object from an existing .xml file to create a feature dataset and creates a grid using the Make Grids And Graticules Layer geoprocessing tool.
import arcpy
import arcpyproduction
# Check out Production Mapping extension
arcpy.CheckOutExtension('foundation')
# Set the values of the tool's parameters using one of the grid
# definition XML files located under the GridTemplates directory
ArcDir = arcpy.GetInstallInfo()['InstallDir']
grid_xml = ArcDir + "/GridTemplates/Quad_24K_NAD83.xml"
# Get the grid's Geographic Coordinate System
grid = arcpyproduction.mapping.Grid(grid_xml)
spatial_ref = grid.baseSpatialReference
grid_gcs = spatial_ref.GCS
grid_dataset_name = grid_gcs.name
# Make a new feature dataset based on the Geographic Coordinate System
fds_result = arcpy.CreateFeatureDataset_management("C:/Project/GridDatabase.gdb",grid_dataset_name,grid_gcs)
# Use the Make Grids and Graticules Layer geoprocessing service to make a grid
lyr_result = arcpy.MakeFeatureLayer_management("C:/Project/AOIs.gdb/QUAD_24K_AOI","QUAD_24K")
arcpy.SelectLayerByAttribute_management("QUAD_24K", "NEW_SELECTION","\"MSNAME\" = 'Raymond California'")
arcpy.MakeGridsAndGraticulesLayer_cartography(grid_xml,"QUAD_24K",fds_result,"QUAD_24K_Grids","MSNAME")
# Check in extension
arcpy.CheckInExtension('foundation')