Best way to import coordinates from .gpx file and display using Google Maps API

15,370

Solution 1

Update for 2020

Works with Google Map's latest API:

<!DOCTYPE html>
<html>
  <head>
    <title>Add Map</title>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=drawing&v=weekly"
      defer
    ></script>
    <style type="text/css">
      #map {
        height: 400px;
        width: 400px;
      }
    </style>
    <script>
        function initMap() {    
            const map = new google.maps.Map(document.getElementById("map"), {
                zoom: 3,
                center: { lat: 0, lng: -180 },
                mapTypeId: "satellite",
                disableDefaultUI: true,
            });
                      
            fetch('2020-10-12_2007.gpx')
                .then(response => response.text())
                .then(str => (new window.DOMParser()).parseFromString(str, "text/xml"))
                //.then(data => console.log(data))
                .then(doc =>
                {
                    var points = [];
                    var bounds = new google.maps.LatLngBounds();
                
                    const nodes = [...doc.getElementsByTagName('trkpt')];
                    nodes.forEach(node =>
                    {
                        var lat = node.getAttribute("lat");
                        var lon = node.getAttribute("lon");
                        //console.log(lat);
                        
                        var p = new google.maps.LatLng(lat, lon);
                        points.push(p);
                        bounds.extend(p);
                    })
                    
                    var poly = new google.maps.Polyline({
                             path: points,
                             strokeColor: "#0000FF",
                             strokeOpacity: 1,
                             strokeWeight: 4
                        });
                        poly.setMap(map);
                        // fit bounds to track
                        map.fitBounds(bounds);
                })
        }
    </script>
  </head>
  <body>
    <h3>My Google Maps Demo</h3>
    <!--The div element for the map -->
    <div id="map"></div>
  </body>
</html>

Solution 2

If you use PostgreSQL database, I'd suggest you to use PostGIS and import your records to the database. Then you can easily generate kml files (ST_asKml) and display them on Google Map. If your gpx is huge, you can use ST_Simplify on a database query so that the page is loaded faster and you still have full detailed route in your database.

You also have a lot of possibilities:

  • search for rides in a specified area
  • measure total distance in a month
  • and much more
Share:
15,370
Brendan Vogt
Author by

Brendan Vogt

Wedding photographer and videographer from Paarl, South Africa. Join me on my new adventure in wedding photography and videography at Brendan Vogt Photo &amp; Video.

Updated on July 20, 2022

Comments

  • Brendan Vogt
    Brendan Vogt almost 2 years

    I am a mountain biker and I track my rides on my Samsung S3 Galaxy using programs such as Endomondo and Strava. Everything regarding my ride is saved on these 2 websites.

    I have my own personal website where I display mountain routes in various areas where I stay. The route data recorded via GPS using Endomondo and Strava I have exported to a .gpx file. I need this data in the .gpx file to display on my own personal website. So I started to look for a solution using the Google Maps API and importing the .gpx file without using an external tool.

    I struggled to find an answer. I came across this post where the guy uses jQuery to extract the data in the XML file and to display this data on his Google map: http://www.jacquet80.eu/blog/post/2011/02/Display-GPX-tracks-using-Google-Maps-API

    This is how implemented it into my HTML markup:

    <script>
         function initialize() {
              var route1Latlng = new google.maps.LatLng(-33.7610590,18.9616790);
              var mapOptions = {
                   center: route1Latlng,
                   zoom: 11,
                   mapTypeId: google.maps.MapTypeId.ROADMAP
              };
              var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    
              $.ajax({
                   type: "GET",
                   url: "gpx/my_route.gpx",
                   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);
                   }
              });
         }
         google.maps.event.addDomListener(window, 'load', initialize);
    </script>
    

    It works. But is this the correct way to do it? Is there a better a way to implement this?

  • Brendan Vogt
    Brendan Vogt about 11 years
    I'm actually using SQL Server. Why would you suggest that I use KML files if I already have them as .gpx?
  • Mr.Pohoda
    Mr.Pohoda about 11 years
    When generating kml from database, you can easily display more routes on the same map. It's also easier to style the route using kml styles.
  • heltonbiker
    heltonbiker almost 11 years
    Kml is the "google way" to store and display geographic data, and both GMaps and GEarth have good support for importing and exporting kml instead of gpx. Also, it's very natural to convert between GPX and KML using tools like, for example, GPSBabel, or even a hack in your favorite language (python, php, etc.)
  • Jimmy Kane
    Jimmy Kane almost 7 years
    @heltonbiker Kml is though not the most popular format and a lot of people not get happy by 'google way'. To my understanding, you can loose information when this conversion happens, such as environmental data etc.