以下是使用ArcPy计算图层要素的折点,并将相邻折点之间距离小于5km的折点记录到CSV文件中的代码:
import arcpy
import math
import csv
# 设置输入和输出路径
input_feature = r"C:\data.gdb\input_feature"
output_csv = r"C:\data.csv"
max_distance = 5000 # 最大距离(单位:米)
# 计算两个点之间的距离,单位为米
def calculate_distance(point1, point2):
deg_to_rad = math.pi / 180.0
earth_radius = 6371000.0 # 地球半径(单位:米)
delta_latitude = (point2.Y - point1.Y) * deg_to_rad
delta_longitude = (point2.X - point1.X) * deg_to_rad
a = math.sin(delta_latitude/2) * math.sin(delta_latitude/2) + \
math.cos(point1.Y*deg_to_rad) * math.cos(point2.Y*deg_to_rad) * \
math.sin(delta_longitude/2) * math.sin(delta_longitude/2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
distance = earth_radius * c
return distance
# 初始化变量
filtered_points = []
# 遍历所有要素
with arcpy.da.SearchCursor(input_feature, ["OID@", "SHAPE@"]) as cursor:
for row in cursor:
feature_id = row[0]
feature_shape = row[1]
# 遍历单个要素的所有折点
vertices = feature_shape.getPart(0)
prev_point = vertices[0]
for i in range(1, len(vertices)):
curr_point = vertices[i]
# 如果当前折点与上个折点之间的距离小于5km,则记录当前折点
distance = calculate_distance(prev_point, curr_point)
if distance <= max_distance:
filtered_points.append([feature_id, curr_point.X, curr_point.Y])
prev_point = curr_point
# 将符合条件的折点写入CSV文件
with open(output_csv, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(['OID', 'X', 'Y'])
for point in filtered_points:
csvwriter.writerow(point)
print(f"已将{len(filtered_points)}个折点写入CSV文件: {output_csv}")
上述代码会遍历指定图层(`input_feature`)的每一个要素及其折点,并计算当前折点与上一个折点之间的距离是否小于5km。如果小于等于5km,则将当前折点的 OID、X 坐标和 Y 坐标记录下来,最后写入 CSV 文件中(`output_csv`)。如果没有符合条件的折点,CSV 文件会保持为空。