如何使用Python访问osgeo/ogr创建的LINESTRING M和MULTILINESTRING M的M值
实现代码
你可以通过遍历几何顶点索引并传入参数调用GetM()的方式提取所有M值,以下是适配两种几何类型的通用函数:
from osgeo import ogr def get_all_m_values(geom): geom_type = geom.GetGeometryName() # 处理LINESTRING M类型 if geom_type == "LINESTRING": m_list = [] for point_idx in range(geom.GetPointCount()): # 传入顶点索引获取对应位置的M值 m_list.append(geom.GetM(point_idx)) return m_list # 处理MULTILINESTRING M类型 elif geom_type == "MULTILINESTRING": m_nested_list = [] for line_idx in range(geom.GetGeometryCount()): sub_line = geom.GetGeometryRef(line_idx) sub_m_list = [] for point_idx in range(sub_line.GetPointCount()): sub_m_list.append(sub_line.GetM(point_idx)) m_nested_list.append(sub_m_list) return m_nested_list else: raise TypeError(f"仅支持LINESTRING M和MULTILINESTRING M类型,当前输入为{geom_type}")
测试验证
使用你提供的示例代码测试结果如下:
# 单线测试 line_wkt = 'LINESTRING M (0 0 5, 0 1 6, 1 1 10)' line_geom = ogr.CreateGeometryFromWkt(line_wkt) print(get_all_m_values(line_geom)) # 输出:[5.0, 6.0, 10.0],如果需要整数格式可在提取时用int()转换 # 多线测试 mline_wkt = 'MULTILINESTRING M ((0 0 5, 0 1 6, 1 1 10), (1 1 10, 2 1 20, 3 1 30))' mline_geom = ogr.CreateGeometryFromWkt(mline_wkt) print(get_all_m_values(mline_geom)) # 输出:[[5.0, 6.0, 10.0], [10.0, 20.0, 30.0]]
原有方案失效原因
GetM()方法默认不传参数时仅返回第0个顶点的M值,必须传入顶点索引才能获取对应位置的M值GetPoints()方法默认仅返回X、Y坐标,不会携带M或Z属性值- 多线几何属于集合类型,不能直接调用针对单个点/线的方法,必须先遍历获取子线几何后再处理,否则会抛出不兼容操作的报错
内容的提问来源于stack exchange,提问作者Felipe D.
相关产品推荐
相关产品推荐

