Search code examples
openlayersgpx

OpenLayers readMetadata from GPX file


I'm using OpenLayers v10.3.1 to display an OpenStreetMap with a GPX derived vector layer on top. I've used the GPX example from the OpenLayers documentation as the basis for my code and it works well showing tracks and waypoints. I want to extract the metadata in the GPX file for which there is a method readMetadata(source) in the GPX class.

Where do I get the source argument from?

I've looked in the GPX code and the source parameter should be an XML node, but as far as I can see the GPX data (an XML document) is not available to me. Has anyone used readMetadata?


Solution

  • Simply fetch the document and pass it as text to the reader

    <!DOCTYPE html>
    <html>
      <head>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/ol.js"></script>
      </head>
      <body>
        <span id="data"></span>
        <script>
    
    fetch('https://www.visugpx.com/download.php?id=mlCYu62cqx')
      .then((response) => response.text())
      .then((text) => {
        document.getElementById('data').innerText =
          JSON.stringify(new ol.format.GPX().readMetadata(text), null, 2);
      });
    
        </script>
      </body>
    </html>