View All Posts

Converting a KML to GeoJSON

Published on Jan 14, 2021 by Ben Tyler

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.jsconst converter = require("@tmcw/togeojson")const fs = require("fs")const DOMParser = require("xmldom").DOMParser// read in our KML file and then parse itconst parsedKML = new DOMParser().parseFromString(  fs.readFileSync("<PATH_TO_KML>", "utf8"))// convert our kml to geojson and store the resultsconst 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.

About Me

Howdy, I am Ben Tyler. I specialize in developing aesthetic and functional websites and applications. I love collaborating on projects, so if you need to hire a developer or an adviser for a project, please get in touch!

Get in touch!