GPX Viewer

The GPX file viewer script can display GPS data in a Google Map. This Google Maps Mashup is written entirely in Javascript and is all client-side scripted. The advantage of this is that it requires no server side scripting. You simply copy some files to your web server and add some content to your web page.

Update 2007/07/31:I have made a Google Code project to host this script. Click here for more details.

Update:Version 4 upgraded to Google Maps API v2.

The GPS data must be in the form of a GPX file. This is an XML based GPS data file format that is supported by many tools. It is nice because it can be used without modification (though size can be a concern if you have a lot of track points). Some information about the tools can be found here.

Since the whole point of this project was originally to show GeoTagged photos, I extended the GPX file format slightly. If a waypoint tag <wpt> contains an <html> within an <extensions> tag then the contents of that tag are inserted in the popup indicator for that map point. In the example below I created a few extra <wpt> tags with just a single image and link embeded in the html. It could, however, contain any html code you wanted.

Note that the code must now be contained with a CDATA element to keep its contents from being parsed by the XML parser. This was needed to get this working in Mozilla/Firefox since they don’t have the .xml property that I was previously using.

Here is an example…

How to use it in your own web page
Here I will give a step by step intro on how to use this script to add a Google Map of your GPS data to any web page.

1. The first thing you need is a GPX file. Many of the GPS tools that I have used support this file format. The WWMX TrackDownload tool only outputs GPX files. You can convert the data from other formats using tools like GPS Babel or online at GPS Visualizer. Due to the way that servers and browsers communicate the type of a file, you will find it much easier of you change the name of the file to end in .xml instead of .gpx.

2. The HTML code for embedding a google map is pretty simple. There is an excellent example at Google called The Hello World of Google Maps. This is a good place to start.

3. Download the Javascript code loadgpx.4.js and save it in the same folder as your web page.

4. The next thing you need to do is modify your google map page to include the file above. Add the following line somewhere in your <head> tag

<script src="loadgpx.4.js" type="text/javascript"></script>

5. Now you can start using the script functions in your own Javascript to load the gpx file and add the track points to the map.

See the Google Maps API Reference for using asynchronous XML for more information on how to dynamically load the XML.

Until I have a real reference page the best thing to do at this point is give an example of how to use the GPXParser object defined in loadgpx.4.js.

Right click on the example below to view the source and see how that page was made.

Examples
Below is a view of this file. It is a GPX file that has been renamed to a .xml extension (needed to convince the browser that it is, in fact, xml). Here is the actual HTML page if you want to view the source http://okuda.ca/googlemaps/gpxviewer.html.

Below this is link to another example using the same script but a different GPX file. This one shows what happens if a waypoint does not have an html tag within it. This file is still quite large so it can take some time to download.

Gold Coast to Great Barrier Reef

Revision History

  • revision 1 – Initial implementation
  • revision 2 – Removed LoadGPXFileIntoGoogleMap and made it the callers responsibility. Added more options (colour, width, delta).
  • revision 3 – Waypoint parsing now compatible with Firefox.
  • revision 4 – Upgraded to Google Maps API version 2. Tried changing the way that the map calculated the way the center and zoom level, but GMAP API 2 requires that you center and zoom the map first. I have left the bounding box calculations commented out in case they might come in handy in the future.

CC-GNU GPL
This software is licensed under the CC-GNU GPL.

63 Responses to “GPX Viewer”

  1. Alice Boit Says:

    great stuff…!
    Only that Firefox doesn’t understand how to load the pictures – it’ll say “undefined” instead of showing the thumbnail.

    >>> Rest of comment removed as it did not format correctly and the GPX viewer has been fixed to work in Firefox <<<

  2. Digg This » Google Maps Based GPX file viewer Says:

    If you like this page feel free to Digg It

  3. Gregor Says:

    Great work!
    I also read your blog about geotagging and I must say I really like it.

    I work as a developer on a web service which you might find interesting:
    http://triptracker.net/.

    TripTracker combines your GPS tracks and your photos and places them on a map. It also solves the time zone problem you had with WWMX.
    Give it a spin and let me know how you like it.

  4. spanring.name Says:

    Bike trails…

    Spring finally arrived in Vienna, sun is shining and I could reactivate my bicycle. Since I go quite often by bike during summer months I decided to start a kind of a “bike project” this year. My bike will serve for another purpose too than…

  5. Notions » Blog Archive » Google Maps API version 2 Says:

    [...] I have upgraded the GPX Viewer mashup script to version 2 of the Google Maps API. There are only some minor changes to the API and some of the objects used. It doesn’t make the script any better, but now it is more likely to be compatible with future versions of the API. [...]

  6. Ronald Says:

    Is it possible to load direct GPX files?
    When i rename an GPX file to xml, it wil be read, but i want to read de GPX file.

    The GPX viewer works only in Firefox, and does’nt work in IE.
    In IE i don’t see the track on the map.

    Am i doing something wrong?

  7. Poco Says:

    The viewer should work in IE. I am using IE to reply to this and am able to view the track logs in the map above. Can you supply a link to your page with the problem.

    As for the GPX file (without the .xml extension). I think it can work, but I have not tried. The trick is to get your server to identify them as xml files. Perhaps it would be possible to write some php script to return the gpx file with an xml header. I have not tried this.

  8. Bets Says:

    I’ve noticed that on some google maps, there are different colour markers.

    eg. http://bluweb.com/us/chouser/gmapez/start.html (scroll to bottom of page)

    is there a way to do this with xml?

    ——-

    alternatively, if i was to use my own markers in place of the default one, where should the code be modified?

  9. Poco Says:

    Ah, I see. If you take a look at that script code you will see that they achieve the different coloured markers by hosting all of them as images on their site. For example, http://bluweb.com/us/chouser/gmapez/iconEZ2/marker-YELLOW-DOLLAR.png.

    My script does not do this, but could easily be modified to support something like this. I have thought of adding markers for the standard GPS waypoints icons. As far as colour, it could be done too by specifying a colour (or icon URL) in the XML and making the appropriate script changes.

  10. chriguhose Says:

    Hi Kaz,

    I’ve used your GpxParser class and build a wordpress plugin around it. I hope you’re okay with it beeing published in the wordpress plugin repository.

    Maybe you would like to add your licence to the source and send me a version that i’m allowed to include in my distribution.

    Cheers and thanks for the great work, you did excatly what i needed.
    chrigu

  11. Mapalizer - » MotoGP Map Says:

    [...] You can open a KML file in Google Maps, but I wanted to work with GPX format as it appears to be the emerging standard. I used the KML2GPX application to quickly change the format. Next step was to figure how to load the GPX file. Without digging into the Google API documentation (I’ll get into that later), I found a great script at a blog called Notions. [...]

  12. Gerben Abbink Says:

    Hi,

    I have found a small error in file loadgpx.4.js (http://okuda.ca/googlemaps/loadgpx.4.js).
    The error occurs in Internet Explorer with test file lewis_clark.gpx (http://www.travelbygps.com/guides/lewis_clark/lewis_clark.gpx).
    In function CreateMarker empty nodes are ignored by testing for nodeType = 1 (elements only).
    However, an elemement “link” may still have no children, such as in lewis_clark.gpx:

    In that case, firstChild is null and an error occurs (firstChild.nodeValue).

    To capture this exception, an extra test is needed:

    115 // Ignore empty nodes
    116 if (children[i].nodeType != 1) continue;
    117 if (children[i].firstChild == null) continue; // “;

    bye,
    Gerben Abbink
    http://www.xmlblueprint.com

  13. Scott Says:

    Great Post!
    Can you tell me how you can change the default setting to “Satellite” view?

    -scott

  14. Poco Says:

    Take a look at the code example in the page above. LoadGPXFileIntoGoogleMap() initializes the map like this. The G_SATELLITE_MAP should make the map default to Satellite view.

    parser.CenterAndZoom(request.responseXML, G_SATELLITE_MAP);

  15. Scott Says:

    Thanks Poco!

    Worked.

    You saved my day.

    -scott

  16. Scott Says:

    Another stupid question if you have the time.
    Do you know how or if it would be possible to force/get the application to load a .gpx?
    I cannot rename the file to .xml (other applications need the .gpx) .
    Is there a way to rename on the fly? SPent several hours searching cannot find the answer.

  17. Poco Says:

    Well, there is no reason why the file must be named .xml. The key is that the server needs to return an xml mime type for the document so the Javascript can parse it correctly. Most servers already return files with .xml extensions as xml mime types so that is why I choose to rename the files for my examples.

    I haven’t tried it, but you can take a look at the mod_mime apache extension to set the mime type of .gpx files returned from the server. You should try something like “application/gpx+xml” and, if that fails, fall back on the default xml mime type “text/xml”.

  18. motomappr :: Geoblogging a Motorcycle Trip Says:

    [...] My intentions was to have the live feeds stored, converted to GPX format and published to my blog. Without the live feeds, I did the plotting and publishing of routes with a series of tools. I started with Google Earth and plotted a route by using the directions feature. If my route was not clear city to city, I would do a series for plots. I would then save these “places” (routes) as a KML file and convert using GPX Visualizer. If there were a couple GPX files, I would splice them together with an editor. To publish with Google Maps, I used the exising API key that I had for motomappr.com, and loaded up the GPX Viewer script. I added a variable to pass a file name, and then simply loaded the GPX files into a folder on my blog and used an iframe setting to integrate into a blog entry. This worked well thanks to the great script work at notions.okuda.ca. As noted the blog is over here. [...]

  19. Gedankengut Says:

    “The GPX viewer works only in Firefox, and does’nt work in IE. In IE i don’t see the track on the map.”

    I could solve this problem by extending the html-Tag:

    Manuel

  20. Gedankengut Says:

    [...] xmlns=”http://www.w3.org/1999/xhtml” xmlns:v=”urn:schemas-microsoft-com:vml” [...]

  21. Unión Montañera Añaza » Archivo del weblog » GPX a GoogleMaps y geolocalización de fotos. Says:

    [...] Incrustar el mapa en nuestro gestor de contenidos (WordPress) fue bastante más complicado, pero esa es otra historia y debe ser contada en otro momento; por ahora comentar que hemos utilizado el plugin Phoogle for WordPress modificado para que leyera archivos gpx. Lo hace usando el código javascript de GPX Viewer. [...]

  22. Ksswa Says:

    Hi!
    First of all: Congratulations!! it’s a very good job.

    One question: is it posible insert the function “to here” in the waypoints of the file .xml?
    For example, A waypoint at the beginning of the route, when you click it, it appears “to here” (it’s a functions of google apis you know).

    Thanks!

    Excuse my english.

  23. mamalovesmambo Says:

    Hi,
    Brilliant! This is exactly what I want to put on my blog.

    Can I use this if my blog is at http://myblogname.blogspot.com/ ?

    I tried putting the loadgpx.4.js into a page element, but it just printed it as text on my blog instead of recognising it as a script.

    How are you pulling in your photos onto the map?
    I’ll have my Geotagged photos on flickr, can I add them from there?

    Also, do you know a way of merging GPX files.
    I am going on a cycle trip and want to add each day’s GPX file into one big GPX file to be displayed on the map, so my whole route over weeks can be seen on the map.

    Hoping you can help!
    Many Thanks

  24. Poco Says:

    Unfortunately, I have had some experience with Javascript in Blogger posts, but it was mostly unsuccessful and a real pain in the butt. I would look around for some examples where people were able to get it to work.

    As for pulling the photos into the map – unfortunately I did that manually using the GPS data that I geotagged into the photos. I do plan to write a tool (server or client side) to automate the process but I have not had the time to do it yet. It would be quite easy to generate a tag like the ones that I have inserted. If anyone wants to write it they are welcome.

    Merging GPX files is easy since they are just text. You can copy the
    sections from one file into the other. Just insert it after the last in the first file.

  25. Marja Says:

    Using this script on a site we’re working on, we have a strange IE only problem on for example the following URL (watch the wrap):
    http://www.wtc-zeewolde.nl/wsadmin/plugins/plugGPSroutes/wsRoute.asp?xmlfile=/uploads/GPSRoutes/88-Stroe.gpx.

    Firefox is just fine on the same URL.

    It throws an error in “GPXParser.prototype.AddTrackSegmentToMap”, on the line that says: “this.map.addOverlay(polyline);”

    The error text is: “Unexpected call to method or property access”, and if we step into that with the Microsoft debugger, we end up on line 29 in the Google API javascript file “http://www.google.com/mapfiles/78/maps2.api/main.js”.

    Does anyone have a clue why this error occurs and what we can do about it?

  26. Marja Says:

    Sorry to have bothered you, the problem is solved.
    My colleague found out that the following namespace declaration was needed for IE to function properly:

  27. Marja Says:

    html xmlns=”http://www.w3.org/1999/xhtml” xmlns:v=”urn:schemas-microsoft-com:vml”

  28. Paranoramix Says:

    hi,

    Just let me to thanks a lot for your job because you method to show gpx files on google map is really good and “speed” (sorry for my english, but I’m french).

    Before, I used google map API function to load KML file but the result tooks a long time to have track on screen and sometime, an error occured :’(

    So, thanks a lot!

    Good bye

  29. DvD del.icio.us bookmarks : June 30, 2007 - July 1, 2007 at Wannaplay.it Says:

    [...] Notions » GPX Viewer : [...]

  30. Thomas Says:

    Hello,

    how can i include “map.setMapType(G_HYBRID_TYPE)” into the script?

    Thanks for the perfekt script, saves a lot of time for me!!

    Thomas

  31. Poco Says:

    As shown on the page above, my example uses the old API call CenterAndZoom to set the map type. You can replace the map type G_SATELLITE_MAP with G_HYBRID_MAP.

    See my upgrade notice when I moved to version 2.
    http://notions.okuda.ca/2006/04/09/google-maps-api-version-2/

    CenterAndZoom seems to have been removed from the API since I wrote the script and replaced with setCenter, but it seems to still work as-is. You can probably also call setMapType after the CenterAndZoom (or setCenter) call to set the type.

    Both of those are documented here…
    http://code.google.com/apis/maps/documentation/reference.html

  32. Kleine Says:

    Is it possible to add Markers to the map after loading the xml file?
    How can I do this.
    I want the user to set extra markers.

  33. Rune Says:

    I discovered a minor bug in the javascript file, on line 240:
    if ( (minlat == maxlat) && (minlat = 0) )
    This is the correct:
    if ( (minlat == maxlat) && (minlat == 0) )

    Anyway, a great script!

  34. Notions » Blog Archive » GPX Viewer is now hosted by Google Code Says:

    [...] I have put the GPX Viewer script (loadgpx.js and some samples) project on Google Code here http://code.google.com/p/gpxviewer/. [...]

  35. Hippocrates In San Diego » Run 7.17.07 Says:

    [...] I think I’ve discovered how to load my Garmin maps into my posts. Thanks to the Notions blog from Canada for help with the code! I’m using Ascent to download runs from my Garmin (highly recommended for you Mac users). [...]

  36. Bert Says:

    Well this was really what I was looking for, very good !!

    I have made a few changes so that I can use the same gpxviewer.html for different gpx files. I used a trick that I found at http://www.htmlgoodies.com/beyond/javascript/article.php/3471111
    I can call gpxviewer in the following way: gpxviewer.html?myfile.gpx
    without using cookies.
    I think that is really nice.
    Look at my site: http://www.bertarends.nl/maps/Gelderland.xml

    Bert

  37. Ben Says:

    Firstly, many thanks for this script – its fantastic. I have it up an running on my blog. One issue I am finding is that the map files are not loading in IE. Works perfectly using FireFox and Safari. Have tried the corrections posted here (updating html, correcting errors on lines 116 and 240).

    Any other ideas?

    Try this link to see:

    http://www.catseries.com/blog/?page_id=16&rideid=2

  38. Keep Friends Posted While on the Road | Code Spatter Says:

    [...] you have a GPS unit that can create xml .gpx files, there are some scripts that will use Google Maps API and let you display waypoints based on those files. We will be using [...]

  39. Rickety Tech Update « Rickety Van Says:

    [...] I’d like to also post semi-realtime GPS data on our website so people can track where we are.  To do this, I will be leaving a GPS running and every so often download the tracking data and upload it to the website.  We can then display it using Google Maps using this software& [...]

  40. Thilo Says:

    I got an error “trackSegment is null” (on line 64) on loading .

  41. Fred Chan Says:

    can the gpx viewer modify to make use file which is using nmea ? b’cos my sms/gps device send back nmea format data, and I can transfer it to website

    Thanks

  42. llsastre Says:

    I’ve tried this excellent script on two websites. On first website it works fine. On second website (www.ciclosblando.com) doesn’t work. I use the same script (with a diferent google api) and the same gpx files, but on the second website comes an javascript error message: “‘this.xmlDoc.documentElement’ is null or it isn’t an object on line 276 char 2.”
    The line error on .js is “var tracks = this.xmlDoc.documentElement.getElementsByTagName(“trk”);”

    You can try at http://www.ciclosblando.com/Rutas/gpxviewer.php?file=D26a
    and at http://www.mallorhouse.com/tmp/gpxviewer.php?file=D26a

    Why means this error? Why it doesn’t happen on first website (www.mallorhouse.com). Maybe a server configuration?

  43. Poco Says:

    The problem above is that the gpx file is not an xml file (at least, the server does not think that it is). The mime type should be “application/xml” or “text/xml” when the server delivers the page so that it is parsed correctly. You can either configure your server to understand that a .gpx file should be returned with this type, or you can change the name of the file. I tend to rename my .gpx files to .xml as most servers do the right thing when delivering a file ending in .xml.

    The easiest way to tell if it is working is to load that file directly into your browser. Many browsers (I know that Firefox, IE, and Chrome do) recoginize that xml files are different from other text files and render them differently. If you just see plain text then the server is not setting the mime type correctly.

  44. llsastre Says:

    Ok. I’ve changed .gpx by .xml and now works perfectly. But I don’t understand why the same file and script works well on mallorhouse.com site.
    Thanks a lot

  45. Raichand Ray Says:

    Hi,
    I have written code referring the Oreilly book google map hacks to display .kml files in google map.I t is working fine.So I am opening .gpx file in notepad and saving as .xml file.

    My questions are

    1. How to code so that it directly accepts .gpx file instead of .kml?
    2.How to display KML files in google map?The code to do it in google API site is not working.

    Thanks

    Raichand

  46. Richard Morrison Says:

    Great bit of code: I plan to use it. I had to set MIME type for .gpx files AND append “?dummy=.xml” to the loaded GPX file to get browsers to really believe they were loading XML.

    Thanks!

  47. Dave Barter Says:

    Kaz

    Thanks for this code. I have added a function that flies a route, you may be interested in it.

    Just needs a new class variable “Marker” and away you go

    Dave

    GPXParser.prototype.FlyMap = function (flypoint)
    {

    var trackpoints=this.xmlDoc.documentElement.getElementsByTagName(“trkpt”);
    var lon = parseFloat(trackpoints[flypoint].getAttribute(“lon”));
    var lat = parseFloat(trackpoints[flypoint].getAttribute(“lat”));
    var currentPoint = new GLatLng(lat, lon);

    if(flypoint == 0)
    this.map.setCenter(currentPoint, 15);

    if(flypoint >= trackpoints.length){
    return;
    }

    if (this.marker != null) {
    this.map.removeOverlay(this.marker);
    }
    this.map.panTo(currentPoint);
    this.marker = new GMarker(currentPoint);
    this.map.addOverlay(this.marker);
    flypoint+=1;

    var _this = this
    window.setTimeout(function(){_this.FlyMap(flypoint)},750);

    }

  48. muddy Says:

    HI firstly i love the script but what i need it to do is calculate the distance, Can this be done ? my script is here http://muddy-bikes.co.uk/trails.php?route=23&title=Lonon%20to%20Brighton

  49. kolyany4 Says:

    Hi!

    I’ve slightly enhanced your script.
    Most important enhancements are …

    1. Added GXmlHttp progress information (usefull when GPX-file is huge).
    2. Auto-updated list of tracks to view each of them separatelly.
    3. Calculated per-track: MAX_SpeedKMpH and DistIn_KM.

    http://kolyany4.narod.ru/gpxviewer.html

    Regards,
    Nick.

  50. The House of Husar Says:

    Hey guys, I have this script working with not having to rename the GPX to an XML. i am also using additional code to get some elevation and speed details. So I did not want to have to rename the files from GPX to XML.

    If you have an Apache server all you have to do is create a .htaccess file in your text editor. Then put the following the file…

    # XML
    AddType text/xml .xml
    AddType text/xml .gpx

    Save the file and upload to the directory that has your GPX script. Now it will handle your GPX as XML and no need to rename them.

    Cheers.

  51. Jesper Says:

    How can I show elevation and speed details with the script ?

  52. knipknap Says:

    Hi,

    Thanks for this, I wrote a small Facebook app using gpxviewer.

    http://apps.facebook.com/gps-maps/

    I also added an ugly hack for supporting .gpx files containing “rte” and “rtept” tags, such as this file:

    http://facebook.debain.org/gpsmaps/routes/14348bb0f844db86265f19a07181c292.xml

    The patched script is here:

    http://facebook.debain.org/gpsmaps/gpxviewer/loadgpx.js

    -Samuel

  53. guido Says:

    working on a mysql en php script to makes my track easier to maintain.
    adding

    AddType application/vnd.google-earth.gpx gpx

    to the .htacces give a sve as, in ff and ie.

    I will use gpxviewer later on.

    guido

  54. Jeroen Says:

    We’ve been using your code for a month or so and
    want to thank you for the great work!

    Jeroen

  55. Steve Smithson Says:

    Any chance of an update for v3 of the API? Great work by the way.

  56. Willian Says:

    Nice work, but whats the benefit to use your gpx-viewer instead of using google’s GGeoXml?

  57. Jay Says:

    Anyway this could somehow be made to work as a script or automator workflow on the Mac? (Right click an image, select “Show on map”, which opens a browser to google maps with a placemark where the photo was taken.)

  58. Local plotting of GPX file onto Google Maps « irq5 Says:

    [...] my search for an local solution (as opposed to uploading it to a server), I found GPX Viewer, an implementation of a GPX parser in Javascript which reads the GPX file and overlays the track. [...]

  59. MSeries Says:

    Another vote for a v3 version here. I’ll try to do it myself but my Javascript skills are very limited, this script is in fact the first time I have tried to modify any Javascript actually. Thanks for posting what you have, it’s so far been very very useful.

  60. Chris Peplin Says:

    Thanks for the great script, Kaz – I updated it for version 3 of the maps API and pushed it to a repository on GitHub. There’s also a little blog post about it here:

    http://christopherpeplin.com/2011/05/gpxviewer/

    The API changed slightly – I made the first letter of the function names lowercase. If you use my version, you’ll have to make that small change in your scripts as well.

  61. iphone app development Says:

    This is a very interesting article. The first thing you need is a GPX file. Lots of of the GPS tools that I have used support this file format. The WWMX TrackDownload device only outputs GPX files. You can convert the knowledge from other formats using tools like GPS Babel or online at GPS Visualizer.Thanks a lot for sharing.

  62. code de la route Says:

    code de la route…

    [...]GPX Viewer « Notions[...]…

  63. Chris Mein Says:

    Fantastic!

    I am in the process of launching a charity to run a real-time passenger information service in New Zealand.

    One of the first projects is to allow people to use a site like Ride With GPS to map their local bus route and save it to a GPX file. Then upload to the Busko Community site and I can then start associating timetable info with it etc.

    Now I thought I would have to struggle away without a good map solution – and then your wonderful script turned up. Thanks so much – just going to fiddle it so I can pipe in my stored GPX data and I will be sorted!

    Chris

Leave a Reply