I like to write almost as much as I like to build. I write about dashboards, maps, freelancing, music, and the outdoors. If this interests you too, please join my mailing list to get updates whenever I publish new content.
Converting a KML to GeoJSON
Time to Read: 1 minutes
Spatial data formats can be a pain to work with, especially if you need to convert between them. On a recent project, I needed a way to easily convert a user uploaded KML or GPX file to GeoJSON in my app so that I could upload it to Mapbox. The solution was surprisingly straightforward. Enter the togeojson package. This project was originally created and maintained by Mapbox but has since been abandoned. Luckily, Tom MacWright (the original author of the Mapbox package), has been maintaining his own fork of the package.
This guide is going to be short and sweet which is a testament to the ease of use of
togeojson. This guide will walk you through how to use the package in a Node.js project.
Before You Start
- Setup a new project directory and run
yarn init -y
- Make sure you have a KML file to convert. If you don't, here is one you can download.
Converting Our KML
To begin, we need to install
togeojson along with
xmldom for xml parsing.
1yarn add @tmcw/togeojson xmldom2
After verifying that it installed correctly, we will create a new file called
index.js and add the following to it, replacing
<PATH_TO_KML> with the path to your KML.
1// index.js2const converter = require("@tmcw/togeojson")3const fs = require("fs")4const DOMParser = require("xmldom").DOMParser56// read in our KML file and then parse it7const parsedKML = new DOMParser().parseFromString(8fs.readFileSync("<PATH_TO_KML>", "utf8")9)1011// convert our kml to geojson and store the results12const geojson = converter.kml(parsedKML)13
And that is it! Now that you have the converter setup, there is a whole slew of other things you can do with the output like....
- write the converted GeoJSON to disk
- transform the GeoJSON, adding or subtracting properties based on the need of your project
- upload the GeoJSON to a platform like Mapbox or Gaia
- add it to a map in your own app
- and the list goes on....
I could go on all day with that list and all things map in general but will leave it here. If you have feedback or comments, please drop me a line below.