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

Date: 1/14/2021

Time to Read: 1 minutes

This post is part of my Building Interactive Maps with React course - a course for anyone wanting to learn how to build interactive maps and integrate them into their React applications. If you enjoy this guide, then chances are you will enjoy the course too!

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.

yarn add @tmcw/togeojson xmldom

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.

// index.js
const converter = require("@tmcw/togeojson")
const fs = require("fs")
const DOMParser = require("xmldom").DOMParser
// read in our KML file and then parse it
const parsedKML = new DOMParser().parseFromString(
fs.readFileSync("<PATH_TO_KML>", "utf8")
// convert our kml to geojson and store the results
const geojson = converter.kml(parsedKML)

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 found thus post useful, give me a follow on Twitter or consider picking up a copy of the Building Interactive Maps with React course.

Join the Newsletter

I periodically send out a newsletter. Interested? Sign up below. You can unsubscribe at any time.

Interested in working together?

Drop me a line
© 2021 Lost Creek Designs