尝试在 Python 中制作 KML 文件

Trying to make a KML file in Python

我对 python 还是很陌生,我正在尝试将列表 (List2) 上的位置导出到 kml 文件中,然后该文件将在 google 地图上显示结果。我真的不知道我在做什么,我得到的只是每个 , 符号周围的语法错误。请有人帮我解决这个问题。

KMLFile = open("KML.txt", "w")
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
    f.write("   <Placemark>")
    f.write("       <decription>" + str(row[0]) + "</description>")
    f.write("       <Point>")
    f.write("          <coordinates>" + str(row[2]) + str(row[1])"</coordinates>")
    f.write("       </Point>")
    f.write("   </Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
KMLFile = close()

在您的代码中,您没有定义变量 f,它应该引用您要写入的文件对象。你可以做

f = open("KML.txt", "w")
f.write("<KML_File>\n")
...
f.close()

或更好:

with open("KML.txt", "w") as f:
    f.write("<KML_File>\n")
    ...

确保始终关闭文件,即使中间的某些代码失败也是如此。

要编写 XML 文件,您可能需要查看 Python xml-package.

简而言之:

  • 您应该将 KMLFile 更改为 f,反之亦然。
  • 您应该像这样调用 close() 方法:f.close().

您更正的代码:

f = open("KML.txt", "w")
f.write("<KML_File>\n")
f.write("<Document>\n")
for line in List2:
    f.write("\t<Placemark>")
    f.write("\t\t<decription>" + str(row[0]) + "</description>")
    f.write("\t\t<Point>")
    f.write("\t\t\t<coordinates>" + str(row[2]) + str(row[1]) + "</coordinates>")
    f.write("\t\t</Point>")
    f.write("\t</Placemark>")
f.write("</Document>\n")
f.write("</kml>\n")
f.close()

另外,如果不想写f.close()行,让python管理文件关闭:

with open("KML.txt", "w") as f:
    f.write("<KML_File>\n")
    f.write("<Document>\n")
    for line in List2:
        f.write("\t<Placemark>")
        f.write("\t\t<decription>" + str(row[0]) + "</description>")
        f.write("\t\t<Point>")
        f.write("\t\t\t<coordinates>" + str(row[2]) + str(row[1]) + "</coordinates>")
        f.write("\t\t</Point>")
        f.write("\t</Placemark>")
    f.write("</Document>\n")
    f.write("</kml>\n")

最后,如果您不想在 f.write() 行中加入很多 +,您也可以选择 format() 方法:

f.write("\t\t\t<coordinates>{}{}/coordinates>".format(row[2], row[1]))

硬编码 XML 输出以在一系列打印语句中创建 KML 文件容易出错且难以维护。而是使用 Python KML 库(例如 simplekml or pyKML)来生成 KML。 simplekml API 简化了 KML 的编写,并使用更清晰、更易于理解的代码生成有效的 KML。

import simplekml

# list2 = ...some assignment with list of point data elements
kml = simplekml.Kml()
for row in list2:
    kml.newpoint(description=row[0],
        coords=[(row[2], row[1])])  # lon, lat, optional height
# save KML to a file
kml.save("test.kml")

将此测试输入用于单个点:

list2 = [ [ 'description', 51.500152, -0.126236 ] ] # description, lat, lon

KML 输出将是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
    <Document id="feat_1">
        <Placemark id="feat_2">
            <description>description</description>
            <Point id="geom_0">
                <coordinates>-0.126236,51.500152,0.0</coordinates>
            </Point>
        </Placemark>
    </Document>
</kml>
import geopandas as gpd

polys = gpd.GeoDataFrame(df) 
polys.to_file(r'../docs/database.kml', driver = 'KML')
  • df 应包含描述、几何图形、名称。