最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Best way to import coordinates from .gpx file and display using Google Maps API - Stack Overflow

programmeradmin4浏览0评论

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:

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?

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?

Share Improve this question asked Apr 5, 2013 at 8:18 Brendan VogtBrendan Vogt 26k39 gold badges150 silver badges235 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

Update for 2020

Works with Google Map's latest API:

<!DOCTYPE html>
<html>
  <head>
    <title>Add Map</title>
    <script
      src="https://maps.googleapis./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>

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
发布评论

评论列表(0)

  1. 暂无评论