Search code examples
callbackopenlayersgpx

Read extensions from GPX features (openlayers)


I am trying to insert GPX data on a Vector Layer and want to later read the attributes inside the tag. This is a small extract from my GPX file:

<gpx xmlns="http://www.topografix.com/GPX/1/1" version="1.1" creator="Catalog to GPX Transformer">
  <wpt lat="49.5486899" lon="8.6643041">
    <name>node_16257516</name>
    <extensions>
      <addr_city>Weinheim</addr_city>
      <addr_country>DE</addr_country>
      <addr_housenumber>31</addr_housenumber>
      <addr_postcode>69469</addr_postcode>
      <addr_street>Bergstraße</addr_street>
      <amenity>fast_food</amenity>
      <brand>McDonald's</brand>
      <brand_wikidata>Q38076</brand_wikidata>
      <brand_wikipedia>en:McDonald's</brand_wikipedia>
      <cuisine>burger</cuisine>
      <indoor_seating>yes</indoor_seating>
      <name>McDonald's</name>
      <opening_hours>PH,Su-Th 09:00-01:00, Fr,Sa 09:00-04:00</opening_hours>
      <outdoor_seating>yes</outdoor_seating>
      <smoking>no</smoking>
      <takeaway>yes</takeaway>
      <website>https://www.mcdonalds.de/</website>
      <wheelchair>limited</wheelchair>
    </extensions>
  </wpt>
</gpx>

Note that not all waypoints have the same extensions. Some may be missing at times.

I found something about an optional readExtensions() callback function that can be passed into the GPX constructor but couldn't find enough information in the documentation or the original GitHub PR for the readExtensions callback function.

How would I implement a readExtensions function and are there other things I need to do in order to then read the extensions from the feature?


Solution

  • In the case of your data a function such as

      readExtensions: (feature, extensions) => {
        const children = extensions.children;
        for (let i = 0; i < children.length; ++i) {
          const element = children.item(i);
          feature.set(element.tagName, element.textContent);
        }
      }
    

    could be used to convert the extension elements into feature properties.