Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
podcast
Filter by Categories
ArcGIS Pro
GDAL
GeoJson
Map
Python
QGIS
Uncategorized

Converting Between KML and GeoJSON: A Comprehensive Guide

Converting Between KML and GeoJSON: A Comprehensive Guide

Geospatial data is often represented in various formats, with KML (Keyhole Markup Language) and GeoJSON being two of the most popular. This guide will provide step-by-step instructions on converting between these two formats using various tools and programming languages.

Quickmaptools.com is by far the easiest way to convert between geojson and KML online. But if you are looking for desktop options continue reading!

Want to stay up to date with all things Geospatial? Listen to our podcast!

Step by Step conversion guides

Converting Between KML and GeoJSON Using QGIS:

Single File Conversion:

  1. Open QGIS.
  2. Go to Layer > Add Layer > Add Vector Layer.
  3. Select the source file (either KML or GeoJSON).
  4. Once the layer is loaded, right-click on it in the Layers panel.
  5. Choose Export > Save Features As.
  6. In the format dropdown, select either KML or GeoJSON, depending on your conversion target.
  7. Specify the file name and location.
  8. Click OK.

Batch Conversion:

  1. Open QGIS.
  2. Go to Processing > Toolbox.
  3. Search for Convert format.
  4. In the Input layer field, use the ... button to select multiple files.
  5. Choose the desired output format (KML or GeoJSON).
  6. Specify the output directory.
  7. Click Run.

Converting Between KML and GeoJSON Using GDAL:

Single File Conversion:

  1. Open the command line or terminal.
  2. Use the ogr2ogr command:
  • For KML to GeoJSON: ogr2ogr -f "GeoJSON" output.geojson input.kml
  • For GeoJSON to KML: ogr2ogr -f "KML" output.kml input.geojson

Batch Conversion:

  1. Navigate to the directory containing your files.
  2. Use a loop to convert all files:
  • For KML to GeoJSON: for i in *.kml; do ogr2ogr -f "GeoJSON" "${i%.kml}.geojson" "$i"; done
  • For GeoJSON to KML: for i in *.geojson; do ogr2ogr -f "KML" "${i%.geojson}.kml" "$i"; done

Converting Between KML and GeoJSON Using ArcGIS Pro:

Single File Conversion:

  1. Open ArcGIS Pro.
  2. Add the source layer to the map.
  3. Right-click on the layer > Data > Export Features.
  4. Choose the desired format (KML or GeoJSON) and specify the output location.
  5. Click Save.

Batch Conversion:

  1. Use the Copy Features tool.
  2. For the input, select multiple files.
  3. For the output, specify the directory and format.
  4. Run the tool.

Converting Between KML and GeoJSON Using Python:

Using the geopandas library:

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')

Batch Conversion:

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')

Converting Between KML and GeoJSON Using R:

Using the sf package:

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")

Batch Conversion:

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))
}

Differences Between KML and GeoJSON File Formats

FeatureKMLGeoJSON
StructureXML-basedJSON-based
Geometry TypesPoint, LineString, Polygon, MultiGeometry, etc.Point, LineString, Polygon, MultiPoint, etc.
AttributesExtendedData elementProperties object
StylingSupported (using Style and StyleMap elements)Not natively supported
SymbologySupportedNot natively supported
Coordinate SystemUses longitude, latitude, altitude (in that order)Uses X, Y, Z (longitude, latitude, altitude)
File SizeTypically larger due to XML verbosityCompact due to JSON structure

Potential Challenges in Conversion:

  1. Geometry Support: While both formats support basic geometries like points, lines, and polygons, KML has unique features like MultiGeometry which might not have a direct equivalent in GeoJSON. This can lead to fragmented or incomplete conversions.
  2. Attribute Handling: KML uses the ExtendedData element to store additional data, while GeoJSON uses the properties object. Mismatched or improperly labeled attributes can result in data loss during conversion.
  3. Styling and Symbology: KML has built-in support for styling and symbology, allowing for detailed customization of how features appear. GeoJSON lacks native styling capabilities, meaning any styling in a KML file might be lost when converting to GeoJSON.
  4. Coordinate Systems: KML uses a specific order for coordinates (longitude, latitude, altitude), while GeoJSON uses the more conventional X, Y, Z order. This can lead to misplaced features if not handled correctly during conversion.
  5. File Structure: Due to the verbosity of XML, KML files are typically larger than their GeoJSON counterparts. This can lead to longer conversion times and larger output files when converting from GeoJSON to KML.
  6. Lossy Conversion: Not all features and attributes in one format have direct equivalents in the other. This can lead to a loss of data or detail during conversion, especially when going from KML to GeoJSON.

Practical Advice:

  1. Pre-Conversion Review: Before converting, review the source file to identify any unique or complex features that might pose challenges. This can help anticipate and address potential issues.
  2. Use Reliable Conversion Tools: Tools like QGIS and GDAL are well-maintained and regularly updated, ensuring accurate and efficient conversions.
  3. Post-Conversion Validation: After conversion, validate the output file to ensure all features and attributes have been correctly transferred. This can be done using geospatial software or online validation tools.
  4. Backup Original Data: Always keep a backup of the original file before conversion to prevent any irreversible data loss.

Comparison:

  • Structure: KML is XML-based, making it more verbose and complex, while GeoJSON’s JSON structure is more compact and human-readable.
  • Geometry Types: Both formats support a wide range of geometries, but KML’s MultiGeometry feature can pose challenges during conversion.
  • Attributes: KML’s ExtendedData element offers flexibility in data storage, while GeoJSON’s properties object provides a more structured approach.
  • Styling: KML’s built-in styling capabilities offer more visual customization than GeoJSON, which lacks native styling features.
  • Coordinate Systems: The difference in coordinate order between the two formats can lead to conversion errors if not handled correctly.

Frequently Asked Questions:

Can I retain the styling of my KML file in GeoJSON?

No, GeoJSON doesn’t natively support styling. However, you can store styling information as attributes and use external libraries to apply them post-conversion

Why are my features misplaced after conversion?

This is likely due to the difference in coordinate order between KML and GeoJSON. Ensure you’re using a reliable conversion tool that handles this difference correctly.

Is there a way to batch-convert multiple files?

Yes, tools like GDAL and QGIS offer batch conversion capabilities. You can also use scripting in Python or R for bulk conversions.

Will I lose any data during conversion?

While both formats are robust, there’s potential for lossy conversion due to differences in features, attributes, and styling. Always validate your output and keep backups of original data.

Which format is better for web applications?

GeoJSON is generally preferred for web applications due to its compact structure and compatibility with many JavaScript libraries.

About the Author
I'm Daniel O'Donohue, the voice and creator behind The MapScaping Podcast ( A podcast for the geospatial community ). With a professional background as a geospatial specialist, I've spent years harnessing the power of spatial to unravel the complexities of our world, one layer at a time.

Leave a Reply