Christophe Jacquet

Display GPX tracks using Google Maps API

Surprinsingly, the Google Maps Javascript API does not provide a built-in way to create an overlay from a GPX track, contrary to OpenLayers for instance.

Forum messages asking a way to add GPX overlays to Google Maps are numerous, and various solutions are proposed. Here I propose my own method, adapted to the Google Maps Javascript API v3. It relies on jQuery, so it is very simple.

The following snippet assumes that a map has been created, and is referenced by the map variable (of type google.maps.Map). After the track has been added to the map, the last instruction zooms to fit the track.

$.ajax({
  type: "GET",
  url: *"URL to the GPX file"*,
  dataType: "xml",
  success: function(xml) {
	var points = [];
	var bounds = new google.maps.LatLngBounds ();
	$(xml).find("trkpt").each(function() {
	  var lat = $(this).attr("lat");
	  var lon = $(this).attr("lon");
	  var p = new google.maps.LatLng(lat, lon);
	  points.push(p);
	  bounds.extend(p);
	});

	var poly = new google.maps.Polyline({
	  *// use your own style here*
	  path: points,
	  strokeColor: "#FF00AA",
	  strokeOpacity: .7,
	  strokeWeight: 4
	});
	
	poly.setMap(map);
	
	*// fit bounds to track*
	map.fitBounds(bounds);
  }
});

Live example

The code works as follows. Retrieve the GPX file using an XMLHttpRequest (“AJAX” request). jQuery parses the file and provides very easy access to the XML tree. For each trkpt (“track point”) node, create a new Google Maps point at the given location. Finally, create a polyline from all these points, and add it to the map.

EDIT 2011-03-07: changed Polygon to Polyline because not all GPX tracks represent closed paths!

EDIT 2011-04-20: using “short” colors (#F0A instead of #FF00AA) no longer appears to work, so I adapted the code.

Valid HTML5? © . ✍ Contact. Imprint (Mentions légales).