首页 > 解决方案 > 我想从 KML 文件中提取坐标

问题描述

我正在尝试从 python 中的 kml 文件中提取坐标,但它给了我错误。下面是我的代码和 kml 文件。

代码:

from pykml import parser

root = parser.fromstring(open('task_2_sensor.kml', 'r').read())
print (root.Document.Placemark.Point.coordinates)

错误:

ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

KML 文件:

                        <coordinates>
                            13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.323018,52.499687,0 13.310096,52.4893,0 13.310096,52.4893,0 13.309909,52.48929,0 13.309909,52.48929,0 13.309753,52.489235,0                            
                        </coordinates>
                    </LineString>
                </Placemark>
                                        
        </Folder>
                
        <LookAt>
            
        </LookAt>
    </Document>
</kml>

标签: pythoncoordinatesextractkmlpykml

解决方案


如果源 KML 具有显式编码,则您必须从 KML 中删除 XML 声明行或使用parse()而不是fromstring()

使用此表单使用 pykml 解析 KML 文件。

with open('task_2_sensor.kml', 'r') as f:
    root = parser.parse(f).getroot()
print(root.Document.Placemark.Point.coordinates)

推荐阅读