-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_kml_file_to_geojson_with_attributes.py
71 lines (58 loc) · 2.45 KB
/
convert_kml_file_to_geojson_with_attributes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# use this script to convert kml file to geojson using GDAL and add attributes to the geojson e.g. area of polygon, name etc
import os
from osgeo import osr
from osgeo import gdal
from osgeo import gdalconst
from osgeo import ogr
# if you are using conda, uncomment these two lines below. chnage username and environmentname
# os.environ['PROJ_LIB'] = 'C:\\Users\\username\\.conda\\envs\\environmentname\\Library\\share\\proj'
# os.environ['GDAL_DATA'] = 'C:\\Users\\username\\.conda\\envs\\environmentname\\Library\\share'
kml_file = 'input_file.kml'
geojson_file = 'output_file.geojson'
kml_driver = ogr.GetDriverByName('KML')
if not kml_driver:
print("KML driver is not available.")
else:
print("KML driver is available.")
kml_datasource = kml_driver.Open(kml_file, 0) # 0 means read-onlyy
if not kml_datasource:
print(f"Failed to open KML file: {kml_file}")
else:
print(f"KML file opened successfully: {kml_file}")
layer = kml_datasource.GetLayer()
geojson_driver = ogr.GetDriverByName('GeoJSON')
if not geojson_driver:
print("GeoJSON driver is not available.")
else:
print("GeoJSON driver is available.")
geojson_datasource = geojson_driver.CreateDataSource(geojson_file)
if not geojson_datasource:
print(f"Failed to create GeoJSON file: {geojson_file}")
else:
print(f"GeoJSON file created successfully: {geojson_file}")
srs = layer.GetSpatialRef()
geojson_layer = geojson_datasource.CreateLayer(layer.GetName(), srs, ogr.wkbMultiPolygon)
# Add 'name' and 'area' fields to the new GeoJSON layer
name_field = ogr.FieldDefn('name', ogr.OFTString)
name_field.SetWidth(256) # Set a maximum width for the name field
geojson_layer.CreateField(name_field)
area_field = ogr.FieldDefn('area', ogr.OFTReal)
geojson_layer.CreateField(area_field)
# Iterate over features in the KML layer
for feature in layer:
# Get the geometry and calculate its area
geometry = feature.GetGeometryRef()
area = geometry.GetArea()
# Create a new feature for the GeoJSON layer
geojson_feature = ogr.Feature(geojson_layer.GetLayerDefn())
# Set the 'name' and 'area' attributes
geojson_feature.SetField('name', kml_file) # Use the KML file name
geojson_feature.SetField('area', area)
# Set the geometry for the new feature
geojson_feature.SetGeometry(geometry)
# Add the feature to the GeoJSON layer
geojson_layer.CreateFeature(geojson_feature)
geojson_feature = None
kml_datasource = None
geojson_datasource = None
print("Done!")