访问量: 574 次浏览

地理空间数据通常以各种格式表示, 其中 KML(Keyhole 标记语言)和 GeoJSON 是最流行的两种格式。 本指南将提供有关使用各种工具和编程语言在这两种格式之间进行转换的分步说明。
单个文件转换:
Layer > Add Layer > Add Vector Layer;Export > Save Features As;OK。批量转换:
QGIS;Processing> Toolbox;Convert format;Input layer 字段中,使用 ... 按钮选择多个文件;Run。单个文件转换:
(1)打开命令行或终端;
(2)使用 ogr2ogr 命令:
ogr2ogr -f "GeoJSON" output.geojson input.kmlogr2ogr -f "KML" output.kml input.geojson批量转换:
(1)导航到包含的文件目录。
(2)使用循环转换所有文件:
for i in *.kml; do ogr2ogr -f "GeoJSON" "${i%.kml}.geojson" "$i"; donefor i in *.geojson; do ogr2ogr -f "KML" "${i%.geojson}.kml" "$i"; done单个文件转换:
Data > Export Features。Save。批量转换:
Copy Features 工具。使用 geopandas 库:
import geopandas as gpd
# For KML to GeoJSON
gdf = gpd.read_file('input.kml')
gdf.to_file('output.geojson', driver='GeoJSON')
# For GeoJSON to KML
gdf = gpd.read_file('input.geojson')
gdf.to_file('output.kml', driver='KML')
批量转换:
import os
import geopandas as gpd
directory = 'path_to_directory'
for filename in os.listdir(directory):
if filename.endswith('.kml'):
gdf = gpd.read_file(os.path.join(directory, filename))
gdf.to_file(os.path.join(directory, filename.replace('.kml', '.geojson')), driver='GeoJSON')
elif filename.endswith('.geojson'):
gdf = gpd.read_file(os.path.join(directory, filename))
gdf.to_file(os.path.join(directory, filename.replace('.geojson', '.kml')), driver='KML')
使用 sf 包:
library(sf)
# For KML to GeoJSON
data <- st_read("input.kml")
st_write(data, "output.geojson")
# For GeoJSON to KML
data <- st_read("input.geojson")
st_write(data, "output.kml")
批量转换:
files <- list.files(path="path_to_directory", pattern="\\.kml$", full.names=TRUE)
for(file in files){
data <- st_read(file)
st_write(data, sub(".kml", ".geojson", file))
}
files <- list.files(path="path_to_directory", pattern="\\.geojson$", full.names=TRUE)
for(file in files){
data <- st_read(file)
st_write(data, sub(".geojson", ".kml", file))
}

实用建议:
比较:
可以在 GeoJSON 中保留 KML 文件的样式吗?
不,GeoJSON 本身不支持样式。 但是,可以将样式信息存储为属性并使用外部库在转换后应用它们。
为什么我的要素在转换后会错位?
这可能是由于 KML 和 GeoJSON 之间的坐标顺序不同造成的。 确保您使用的是可靠的转换工具, 可以正确处理这种差异。
有没有办法批量转换多个文件?
是的,GDAL 和 QGIS 等工具提供批量转换功能。 您还可以使用 Python 或 R 中的脚本进行批量转换。
转换过程中我会丢失任何数据吗?
虽然这两种格式都很强大, 但由于功能、属性和样式的差异, 可能会出现有损转换。 始终验证您的输出并保留原始数据的备份。
哪种格式更适合 Web 应用程序?
由于结构紧凑且与许多 JavaScript 库兼容, GeoJSON 通常是 Web 应用程序的首选。