提供一个平时工作中经常使用的代码:根据经纬度范围,自动将数据找到对应的UTM投影,并进行投影变换。
注意:
- 1. 输入图层需采用地理坐标系(如EPSG:4326)
- 2. 对应修改输出目录和图层名称。
代码如下
# -*- coding: utf-8 -*-
from qgis.core import (
QgsProject,
QgsVectorLayer,
QgsCoordinateReferenceSystem,
QgsCoordinateTransform,
QgsVectorFileWriter,
QgsRectangle,
)
import os
import re
# === 1. 获取图层 ===
layer = QgsProject.instance().mapLayersByName("河流t")[0]
print(f"✅ 使用图层:{layer.name()}(CRS: {layer.crs().authid()})")
# === 2. 计算 UTM 带(WGS84)===
ext = layer.extent()
center_x = (ext.xMinimum() + ext.xMaximum()) / 2
center_y = (ext.yMinimum() + ext.yMaximum()) / 2
utm_zone = int((center_x + 180) // 6) + 1
epsg_code = 32600 + utm_zone if center_y >= 0 else 32700 + utm_zone
utm_crs = QgsCoordinateReferenceSystem(f"EPSG:{epsg_code}")
print(f"🎯 UTM 带:第 {utm_zone} 带 → EPSG:{epsg_code}")
# === 3. 构建坐标变换 ===
transform_context = QgsProject.instance().transformContext()
transform = QgsCoordinateTransform(layer.crs(), utm_crs, transform_context)
# === 4. 准备导出选项 ===
options = QgsVectorFileWriter.SaveVectorOptions()
options.driverName = "GPKG"
options.fileEncoding = "UTF-8"
options.layerName = f"{layer.name()}_UTM{utm_zone}"
# === 5. 执行导出 ===
output_path = r"D:\output\河流t_UTM48.gpkg"
os.makedirs(os.path.dirname(output_path), exist_ok=True)
error_code, new_filename, new_layername, error_msg = QgsVectorFileWriter.writeAsVectorFormatV3(
layer=layer,
fileName=output_path,
transformContext=transform_context,
options=options,
)
# === 6. 输出结果 ===
if error_code == QgsVectorFileWriter.NoError:
print(f"✅ 成功导出:{new_filename}")
# 自动加载结果图层
result_layer = QgsVectorLayer(new_filename, f"[UTM{utm_zone}] {layer.name()}", "ogr")
if result_layer.isValid():
QgsProject.instance().addMapLayer(result_layer)
print("🖼️ 已加载结果图层")
else:
print(f"❌ 导出失败({error_code}):{error_msg}")
计算UTM带号原理
对于任意一点的 经度(λ,单位:度),其所属 UTM 带号按如下公式计算:
带号 = floor((λ + 180) / 6) + 1
- λ 是东经为正、西经为负的十进制度数(例如:北京 ≈ 116.4°,拉萨 ≈ 91.1°,纽约 ≈ −74.0°);
- floor() 表示向下取整(即舍去小数部分);
- +180 是为了将经度范围从 [−180, +180) 平移到 [0, 360),便于整除;
- /6 是因为每带宽 6°;
- +1 是因带号从 1 开始编号(不是从 0)
更多算法问题,欢迎留言或联系我们。转载须注明出处。