Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 544
Brendan Vogt Avatar asked Apr 05 '13 08:04

Brendan Vogt


People also ask

Does Google Maps use GPX files?

Google Maps uses the KML format for its map data, but they support many formats, including GPX.

How do I view a GPX route?

How to open a GPX file. The easiest way to open a GPX file and view the map data it contains is by uploading it to the web version of Google Maps. After you open and sign in to Google Maps in your web browser, you can add a GPX file as a new map by: Opening the Google Maps menu and selecting Your places.

How do I import a GPX file into a locus map?

If you don't have GPX set as the default export format, tap the item under the Export type title and select GPX. Name your track, define the storage place (again we recommend Dropbox) and export. On the Bikemap.net, click the “Upload” button in the upper right “New route” menu. Find your file on Dropbox and import.


2 Answers

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
like image 87
Mr.Pohoda Avatar answered Oct 14 '22 04:10

Mr.Pohoda


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>
like image 24
Fidel Avatar answered Oct 14 '22 03:10

Fidel