Skip to main content

代码片段

前置编码

import arcpy, sys

reload(sys)
sys.setdefaultencoding("utf-8")

中文处理

# 判断是否存在中文字符
def is_ascii(input_str):
try:
input_str.decode("ascii")
return True
except UnicodeDecodeError:
return False

# 如果存在则进行编码
def path_decode(mxd_path):
if not is_ascii(mxd_path):
return mxd_path.decode("utf-8", errors="ignore")

return mxd_path

获取当前打开的mxd实例

mxd = arcpy.mapping.MapDocument("current")

mxd_path = "d:/temp/我们/template.mxd".decode("utf-8")

mxd = arcpy.mapping.MapDocument(mxd_path)

获取当前视图图层

# 无差别获取所有图层
layers = arcpy.mapping.ListLayers(mxd)

# 列出所有图层信息
for lyr in arcpy.mapping.ListLayers(mxd):
print(lyr.name)

获取

列出所有图层

mxd = arcpy.mapping.MapDocument("current")

df = arcpy.mapping.ListDataFrames(mxd)
if len(df) > 1:
for each_df in df:
each_df.name

layer_list = arcpy.mapping.ListLayers(mxd)
target_layer_name = "流速"

print(len(layer_list))

for lyr in layer_list:
lyr.name

列出所有图层组

    layers = arcpy.mapping.ListLayers(df[0])
for each_layerset in layers:
if each_layerset.isGroupLayer and each_layerset.name == layer_set:
pass

获取文件夹下所有.mxd文件

def list_files(directory, extension, recursive=False, max_depth=300, current_depth=0, exclude_extension="_template"):
file_paths = []

if current_depth > max_depth:
return file_paths

try:
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
basename, _ = os.path.splitext(filename)

if os.path.isfile(filepath) and filename.endswith(extension) and not basename.endswith(exclude_extension):
file_paths.append(filepath)

elif os.path.isdir(filepath) and recursive:
file_paths.extend(
list_files(filepath, extension, recursive, max_depth, current_depth + 1, exclude_extension)
)

except OSError:
pass # Handle permission errors or other issues gracefully

return file_paths

mxd_file_list = list_files(config.mxd_path, ".mxd", exclude_extension="_template")

数据驱动

视图相关属性

dataDraven =  mxd.dataDrivenPages

# 获取当前数据驱动显示的范围几何对象
shape = mxd.dataDrivenPages.pageRow.shape

导出页面单独图片(JPG,mxd)

# 获取当前页面实例
mxd = arcpy.mapping.MapDocument("current")

# 获取页面的总数
pageCount = mxd.dataDrivenPages.pageCount

# 遍历页面
for pageNum in range(1, pageCount+1):

# switch page
mxd.dataDrivenPages.currentPageID = pageNum
mxd.saveACopy(os.path.join(output_dir, output_name+'_'+str(pageNum)+'.mxd'))

arcpy.mapping.ExportToJPEG(mxd, os.path.join(output_dir, output_name+'_'+str(pageNum)+'.jpg'), resolution=50)


# 导入关键模块
import arcpy

# 获取入参
# 入参的索引从0开始
output_dir = arcpy.GetParameterAsText(0)

try:
# 业务处理
arcpy.AddMessage("当前入参1为: " + output_dir)

# 获取当前页面实例
mxd = arcpy.mapping.MapDocument("current")

except Exception as e:
# 错误处理
# 此处使用utf-8,支持中文输出到gis的控制台
arcpy.AddMessage("错误原因: " + e[0])

获取shp文件的范围(矩形)

import arcpy, sys
from decimal import Decimal

reload(sys)
sys.setdefaultencoding("utf-8")


def get_shp_shap(shapefile_path, decimal_places=8):
"""
@Description 获取shp文件的左上角,右下角坐标

- param shapefile_path :{param} 要提取的shp文件绝对路径
- param decimal_places=8 :{int} 要保留的小数点,默认为6

@returns `{tuple[str]}` (xmin, ymin, xmax, ymax)

@example

```python
shp = "W:/CPS/MyProject/python-tools/gis-api/static/upload/mikeio/res/河道范围/河道范围.shp"
startX, startY, endX, endY = get_shp_shap(shp)

print("start: {0} {1}".format(startX, startY))
print("end: {0} {1}".format(endX, endY))
```

"""
# 使用 Describe 函数获取 Shapefile 的描述对象
desc = arcpy.Describe(shapefile_path)

# 获取 Shapefile 的扩展对象
ext = desc.extent

# 提取对角坐标,保留8位小数点
xmin = format(ext.XMin, ".{}f".format(decimal_places))
ymin = format(ext.YMin, ".{}f".format(decimal_places))
xmax = format(ext.XMax, ".{}f".format(decimal_places))
ymax = format(ext.YMax, ".{}f".format(decimal_places))

return (xmin, ymin, xmax, ymax)

判断是否shp文件图层

def is_legal_shp_layer(layer):
"""
@Description 判断图层是否合法的数据图层,且是否关联着shp文件

- param layer :{param} {description}

@returns `{}` {description}

"""
try:
# 判断是否图层组
if layer.isGroupLayer:
return False

# 判断是否关联了shp文件,且shp文件是否真实存在
if layer.supports("DATASOURCE"):
data_source = layer.dataSource
if not os.path.exists(data_source):
return False

if not str(data_source).endswith(".shp"):
return False

return True

return False
except Exception as e:
return False

过滤字段

  • 仅限制长度
def test(Contour, Shape_Length):
Contour = float(round(Contour, 2))
length = int(Shape_Length)
limt = 1000

if length >= limt:
if Contour==0:
return "流速不变"
elif Contour>0:
return "流速增大"
else:
return "流速减少"
else:
return ""
test(!Contour!, !Shape_Length!)

限制长度等值线范围

def test(Contour, Shape_Length):
Contour = float(round(Contour, 2))
length = round(Shape_Length, 2)
limt = 900
contour_limt = [0, 0.01, -0.01, 0.03, -0.03]

if length >= limt and Contour in contour_limt:
if Contour == 0:
return "流速不变"
elif Contour > 0:
return "流速增大"
else:
return "流速减少"
return ""
test(!Contour!, !Shape_Length!)

仅过滤流速变化

def test(Contour):
Contour = float(round(Contour, 2))

if Contour == 0:
return "流速不变"
elif Contour> 0:
return "流速增大"
else:
return "流速减少"

test(!Contour!)

标注相关

根据某字段显示

// 假设当前字段名称为 
// static字段,记录了三种状态
// 流速增大、流速不变、流速减小
// 就算字段为空,在length中也会显示为1,所以指定为4的才显示
function FindLabel ( [static], [Contour] )
{
tar = [static].toString()
if( tar.length == 4 ) { return [Contour] }
return "";
}
// 添加条件限制
function FindLabel ( [static], [Contour], [Shape_Length] )
{
var tar = [static].toString()
var limt = 300

if(tar != "" && [Shape_Length] >= limt) return [Contour]

return "";
}

根据数据驱动页分割mxd

遇到一个无法必须要将数据驱动的mxd分割出每一页的需求,中途要对每个分割的mxd人工修改,然后再批量导出成pdf或者jpg,以下是核心代码

def split_mxd(mxd_path, output_dir, outout_ext="mxd", with_small_img=False):
mxd = arcpy.mapping.MapDocument(mxd_path)
output_name, _ = path.splitext(path.basename(mxd_path))

# 获取页面的总数
pageCount = mxd.dataDrivenPages.pageCount
print("pageCount: ", pageCount)
if pageCount <= 1 or not pageCount:
print("没有数据驱动相关数据")
return

for pageNum in range(1, pageCount + 1):
mxd.dataDrivenPages.currentPageID = pageNum
mxd.saveACopy(
path.join(
output_dir, "{}_{}.{}".format(output_name, str(pageNum), outout_ext)
)
)

if with_small_img:
# 50dpi的小图
arcpy.mapping.ExportToJPEG(
mxd,
path.join(output_dir, output_name + "_" + str(pageNum) + ".jpg"),
resolution=50,
)