最开始,我使用的是QGIS工具箱里的创建网格工具去生成经纬网格数据,但是由于18级的经纬网格数据量过大,内存不够用,电脑直接崩掉,且生成的格网数据为一个个的矩形,数据类型为polygon,不方便后续操作,从而改用python脚本处理数据,代码如下:
import geopandas as gpd
from shapely.geometry import Polygon, LineString
def create_grid_lines(x_min, x_max, y_min, y_max, cell_size):
# 确保 cell_size 大于 0
if cell_size <= 0:
raise ValueError("Cell_size必须大于0")
# 生成经纬度网格
lines = []
# 计算步长
step = int(cell_size * 100000)
# 检查计算的步长
if step <= 0:
raise ValueError("计算的步长必须大于0,检查cell_size.")
print(f"步长: {step}") # 打印步长,便于调试
# 计算总的步骤数量以便于显示进度
num_x_steps = (int(x_max * 100000) - int(x_min * 100000)) // step
num_y_steps = (int(y_max * 100000) - int(y_min * 100000)) // step
total_steps = num_x_steps * num_y_steps
current_step = 0
for x in range(int(x_min * 100000), int(x_max * 100000), step):
for y in range(int(y_min * 100000), int(y_max * 100000), step):
# 创建矩形的四条边对应的线段
lines.append(LineString([
(x / 100000.0, y / 100000.0),
(x / 100000.0, (y + step) / 100000.0), # 左边
]))
lines.append(LineString([
(x / 100000.0, (y + step) / 100000.0),
((x + step) / 100000.0, (y + step) / 100000.0), # 上边
]))
lines.append(LineString([
((x + step) / 100000.0, (y + step) / 100000.0),
((x + step) / 100000.0, y / 100000.0), # 右边
]))
lines.append(LineString([
((x + step) / 100000.0, y / 100000.0),
(x / 100000.0, y / 100000.0), # 下边
]))
current_step += 1
# 打印当前进度
if current_step % (total_steps // 100) == 0: # 每0.001%的进度
print(f"进度: {current_step / total_steps * 100:.2f}%")
return gpd.GeoDataFrame(lines, columns=['geometry'])
# 设置台湾区域和网格大小
x_min, x_max = 119.62, 122.25 # 经度范围
y_min, y_max = 21.84, 25.35 # 纬度范围
cell_size = 0.001
# 确保 cell_size 是一个正确的值,类型也正确
print(f"Cell size: {cell_size}") # 打印 cell_size,便于调试
# 创建线网格
grid_lines = create_grid_lines(x_min, x_max, y_min, y_max, cell_size)
# 导出为 shapefile
grid_lines.to_file("grid_taiwan_lines.shp")
print("生成grid_taiwan_lines.shp")
执行该脚本需要import geopandas as gpd from shapely.geometry import Polygon, LineString
如果本地环境不方便安装可在虚拟环境下执行