DEV Community

Cover image for Converting a KML to GeoJSON
Ben Tyler
Ben Tyler

Posted on • Edited on • Originally published at lostcreekdesigns.co

Converting a KML to GeoJSON

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (1)

Collapse
 
boobo94 profile image
Bogdan Alexandru Militaru

Hi Ben. Nice series of articles.

These days I had to handle the KML and KMZ files in Nodejs and I wrote a small article about that. Hope you and community find this helpful - boobo94.github.io/tutorials/create....

Thanks for your article!