Geopandas保存KML文件时未包含属性列问题求助
解决Geopandas导出KML后Google Earth不显示属性的问题
我之前也碰到过类似的情况,Geopandas默认导出KML时,并不是所有属性都会被正确写入到Google Earth能识别的位置,尤其是带空格、特殊符号的字段名(比如你的Final Action (Coverage)),很容易被忽略。下面给你两种可行的解决方案:
方案一:指定Schema强制保留属性字段
Fiona的KML驱动默认可能不会包含所有属性,我们可以手动定义schema,明确告诉它要保留哪些字段。另外,带空格和括号的字段名在KML里兼容性较差,建议先重命名字段:
import geopandas as gpd import fiona # 启用KML读写支持 fiona.supported_drivers['KML'] = 'rw' gpd.io.file.fiona.drvsupport.supported_drivers['KML'] = 'rw' # 截取目标数据 a = df_geom[['Geohash_8','Geohash_7','Final Action (Coverage)','geometry']].head(3) # 重命名带特殊字符的字段,避免兼容性问题 a_clean = a.rename(columns={'Final Action (Coverage)': 'Final_Action_Coverage'}) # 定义KML的schema,明确指定要包含的属性 schema = { 'geometry': 'Polygon', 'properties': { 'Geohash_8': 'str', 'Geohash_7': 'str', 'Final_Action_Coverage': 'str' } } # 保存时传入schema参数 a_clean.to_file('test_fixed.kml', driver='KML', schema=schema)
导出后在Google Earth里右键点击多边形,选择「属性」,就能在「扩展数据」标签里看到这些属性了。
方案二:用simplekml手动生成KML(更灵活可控)
如果觉得Fiona的驱动不够灵活,推荐用simplekml库,它能完全自定义KML的每一部分,包括属性字段的写入:
首先安装依赖:
pip install simplekml
然后编写代码:
import simplekml import geopandas as gpd a = df_geom[['Geohash_8','Geohash_7','Final Action (Coverage)','geometry']].head(3) # 初始化KML对象 kml = simplekml.Kml() # 遍历每条数据,创建多边形并添加属性 for _, row in a.iterrows(): # 创建多边形,用Geohash作为名称方便识别 poly = kml.newpolygon(name=row['Geohash_8']) # 提取多边形的坐标(注意shapely对象的exterior.coords需要转成列表) poly.outerboundaryis.coords = list(row['geometry'].exterior.coords) # 添加扩展属性,字段名可以保留原格式 poly.extendeddata.newdata(name='Geohash_8', value=row['Geohash_8']) poly.extendeddata.newdata(name='Geohash_7', value=row['Geohash_7']) poly.extendeddata.newdata(name='Final Action (Coverage)', value=str(row['Final Action (Coverage)'])) # 保存KML文件 kml.save('test_custom.kml')
这种方法生成的KML,Google Earth能完美识别所有属性,而且你还能自定义多边形的样式、颜色等,非常灵活。
小提示
Google Earth查看属性的正确方式是:右键点击地图上的多边形 → 选择「属性」→ 切换到「扩展数据」标签,就能看到所有你添加的属性字段啦。
内容的提问来源于stack exchange,提问作者ahmad fairuz
相关产品推荐
相关产品推荐

