Converting a KML to GeoJSON

Converting a KML to GeoJSON

·

4 min read

This post is part of the forthcoming Mapbox Developer's Handbook - a comprehensive guide for anyone building interactive maps and applications using Mapbox. You can pick up a copy here!

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 this post useful, please retweet, share, or pick up a copy of The Mapbox Developer's Handbook!