Reducing coordinate density in KML files (with a node.js script)

June 30, 2012

Lately I’ve been tracking my bicycle rides with an Android GPS tracking app. The app exports to multiple formats, including Google Maps and KML. I wanted to take all my rides for a week and overlay them on a single map, but the coordinate density was too high - thousands of points for each ride - so GMaps was paginating the maps to reduce the density, and the overlays didn’t work.

So I needed some way to reduce the coordinate density of the KML files, taking 1 out of every N points, so the route looked the same on the map but with less unnecessary detail.

I tried to find an existing tool to do this, but couldn’t find one. So I started writing one as a node.js script (I’m trying to do everything platform-neutral these days in node). First I tried to actually parse the KML using various XML parsers - but the parsers stripped the line breaks between coordinates, so the format broke, and I realized I didn’t really need to parse the format at all. I just needed to eliminate some of the lines.

The result is a very simple, functional KML Coordinate Density Reducer. It reads each line of a KML file, uses regex to determine if it’s a coordinate line or not, and if it is a coordinate line, strip all but every Nth line, as specified in the shell parameters.

Using the script, I reduced each route from thousands of points to a few hundred, imported them all into a single map, and can view or embed the routes all at once.

Update: Someone wrote an adaptation that also checks the distance between points. (See tweet.)