Generating GPX and KML maps with Ruby on Rails

While working on my various projects, I’ve dealt with various types of maps.

My Flight Historian plots flight data using the Great Circle Mapper tool. These maps are simple to generate from my flight data (I just have to pass it a plain text collection of airport codes) and easy to embed in my website. However, because they are static images, they can’t be easily panned, zoomed, or otherwise manipulated in the way that modern map websites and apps can.

A sample Great Circle Mapper map of my flights in 2018.
(Map generated by Paul Bogard using the Great Circle Mapper – copyright © Karl L. Swartz)

On the other hand, my driving maps require too much detail for a single image, so I create them in Google Earth, which lets me manipulate the view as much as I need to. The driving data is a bit more complicated than my flight log data; while my flight log represents the abstract shortest distance straight line between two airports (and thus only requires specifying the airport at each end), a single drive can involve tens of thousands of coordinates that can be joined together, connect-the-dots style, to show the actual driving route taken.

A sample driving data map using Google Earth

Fortunately, all those coordinates are automatically generated and saved by my car’s GPS navigation unit in a file format called GPX (GPS Exchange Format), which is an XML-based file format which contains (among other things) latitude/longitudes sampled, in the case of my particular GPS, once per second.

Sample from a GPX file from a recent trip

Google Earth doesn’t use GPX format (though it can import it); instead, it uses a format called KML (Keyhole Markup Language, from back when Google Earth was Keyhole EarthViewer). KML is also an XML-based format, so conceptually it’s similarly a collection of coordinates that can all be joined together, with its own slightly different style.

The same set of latitudes, longitudes, and altitudes in KML format. (Note that KML reverses the order of longitude and latitude.)

But while GPX and KML can be used to represent complicated route shapes, they don’t have to be. These formats are both just as capable of taking a pair of points on the globe and drawing the shortest line between them. With that in mind, I decided to try to have Flight Historian automatically generate KML and GPX versions of my flight map, which would let me show my flight routes in Google Earth and Google Maps.

Overall Strategy

I already had a Map class for generating Great Circle Mapper maps, which had several more specific child classes (FlightsMap,
SingleFlightMap, HighlightedRoutesMap, AirportsMap, andAirportFrequencyMap. Each of these child classes would accept certain combinations of airports and flight routes when a new instance was created, and would distill them down to arrays of airports (a separate array for each map airport display style, such as airports_normal or airports_highlighted, in the format [1,2,3]) and arrays of pairs of airports (a separate array for each map route display style, such as routes_normal or routes_highlighted, in the format [[1,2],[3,4],[5,6]]).

The parent Map class had a draw method which would use these arrays to generate the HTML necessary to embed a Great Circle Mapper map image.

Since Map already did the work of converting all the various map styles into airport and route arrays, I decided that I could make Map more generic so it could also create GPX and KML maps. I renamed the Map.draw method to Map.gcmap (which still returns HTML), and created new Map.gpx and Map.kml methods, both of which return XML.

Creating Map.gpx

As far as Ruby on Rails is concerned, creating XML isn’t substantially different from creating HTML. Effectively, you can use the same technique you’d use to return inline HTML in a helper method.

Of course, to have a Class act like a Helper, I needed to explicitly include some ActionView modules (which I’d already done for the gcmap HTML):

GPX Structure

I needed to generate XML tags in accordance with the GPX standard. The basic structure of XML I needed to generate was as follows:


The <metadata> section was pretty simple, as it’s just a static string. (Technically, it needed to be an ActiveSupport::SafeBuffer to get the raw XML, since Rails escapes HTML/XML it finds in strings. A SafeBuffer is what you get when you run .html_safe on a string, though it’s better to use content_tag since .html_safe can be pretty dangerous when used on anything non-static. However, I do use html_safe on the XML prolog, since that never changes, and content_tag can’t handle that syntax.)

Waypoints (Airports)

The <wpt> tags required that I loop over the airport arrays, generating XML tags for each. Specifically, the way I wrote Map, the airport arrays are arrays of airport IDs from my Airports database. The Map class already had a class variable @airport_details which is a hash of all airports used by the map, in the following format:

@airport_details[9] = {iata: "ATL", icao: "KATL", latitude: 33.63670, longitude: -84.42786, city: "Atlanta", country: "United States"}

I created a gpx_airports method which would accept an array of airport IDs and loop through them, and a gpx_airport method which would generate the XML for a specific waypoint:

Note that the gpx_airport method has a wpt_type parameter. This is because while GPX waypoints are contained within a <wpt> tag, GPX route tags also contain a collection of routepoints, which are functionally identical to waypoints but are contained within a <rtept> tag. Thus, I wrote the function so it could be used for either, and the wpt_type parameter specified which type I wanted to use.


Similarly, I wrote a gpx_routes method to loop over an array of pairs of airport IDs, and a gpx_route method to generate the appropriate XML for a specific route:

Completing the gpx Method

For GPX (unlike for gcmap), I wasn’t planning to format different categories of airport or routes differently, since the GPX format doesn’t really have formatting without using extensions. Thus, I could just loop over the keys of the entire @airport_details hash, rather than bothering with airports_normal, airports_highlighted, etc. Routes didn’t have quite a simple way to merge them all, so I just ended up doing a set union (|) between all of my routes arrays.

And with that, calling gpx on an instance of map will return a SafeBuffer containing GPX-formatted XML.

Creating Map.kml

Conceptually, creating KML was pretty similar to creating GPX – create an XML structure, and loop through airports and routes to create XML elements. However, KML does have somewhat more support for styling, so while I chose to maintain a single style for all airports, I did end up distinguishing between the various types of routes.

KML Structure

The KML standard produces a document like this:

Metadata and Style

Unlike GPX, KML doesn’t have a specific <metadata> tag. Instead, metadata (like name and description) are kept in the main <Document> element.

KML supports named styles within a <Style> tag, also kept in Document. I defined a specific icon for airports, and defined a red line with a width of two for route lines. (Note that the colors are defined as a hexadecimal color with alpha, but instead of RRGGBBAA, it’s AABBGGRR.)

I created a kml_styles method to keep these in one place:

Points (Airports)

The basic map element for KML is the <Placemark>. While these can be put directly in the <Document> element, they can also be placed in a <Folder> (if you’ve seen folders in the left sidebar on Google Earth, that’s what these are). I decided I’d create a folder for Airports, and (in the next section) a folder for Routes. The folder has a <name>, and a <Placemark> for each airport.

In order to use the icon style I defined above, I needed to include the name of the style with <styleUrl>#airportMarker</styleUrl>.

The <Placemark> contains a <Point>, which contains <coordinates>. Note that the coordinates are in longitude,latitude,altitude order, NOT latitude,longitude,altitude.

I created a kml_airports method which would loop through an array of airport IDs, and a kml_airport method which would generate the XML for a specific point:

LineStrings (Routes)

Similarly, I created a <Folder> for routes. I still needed to use <Placemark> tags to create lines, but within them are <LineString> tags.

For long-distance lines (such as flight routes), the <tessellate>1</tessellate> option needs to be included to prevent the line from clipping below the terrain.

The <coordinates> uses the same longitude,latitude,altitude format as points did above, but since it’s a line, it needs multiple coordinates, which are all kept within the same tag, space-separated.

Not surprisingly, I wrote kml_routes and kml_route methods to create a collection of routes (from an array of pairs of airport IDs) and an individual route, respectively:

Completing the kml Method

Putting it all together looks pretty similar to what I did for GPX, though I did end up separating my different route types in different folders:

Serving the XML

I wanted to make a GPX and KML map of all of my flights downloadable, which meant I needed to render them effectively as XML views (as opposed to the usual HTML or HTML ERB views of a Ruby on Rails application).

Fortunately, rendering an XML view is not much different from rendering an HTML view.

Controller Actions

First, I needed to create a controller action for each of the XML maps. Since I was creating flight maps, I decided to place them in app/flights_controller.rb: is a method I already had to return all flights that a user of the site has permission to see.

Normally, Rails would automatically look for a view matching the name of the controller action. However, I overrode that behavior here and explicitly told Rails to render an XML document instead by using the render xml: syntax. (This also meant I didn’t need to add anything to the /views/flights folder!)

As discussed above in Overall Strategy, FlightsMap is a child class to Map, and so it responds to both .gpx and .kml by returning XML.

So effectively, each controller action gets all flights the user has permission to, creates a map, gets the GPX or KML XML data from that map, and renders it as XML.


While Rails doesn’t require a file extension on routes, I was ultimately trying to generate KML and GPX files, so I went ahead and gave the routes .kml and .gpx extensions so they had a logical filename when downloaded.

Sample Output


Conceptually, generating GPX and KML (or any kind of XML) aren’t too different from creating a standard HTML/ERB view in Rails – either one is just a matter of generating the right tags.

I still want to spend some time playing around with styles in KML in particular. I’d also like to add more metadata to each waypoint/point and route/linestring (such as number of times visited or flown, distance, etc.).

But for now, I can export my flight maps into other mapping applications!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s