mpetazzoni / leaflet-gpx

A GPX track plugin for Leaflet.js
http://mpetazzoni.github.io/leaflet-gpx
BSD 2-Clause "Simplified" License
529 stars 114 forks source link

Get latLng #145

Closed strukturart closed 11 months ago

strukturart commented 11 months ago

Hello,

is it possible after loading a gpx file to get an array with the latLng ? I want to use this to determine how close I am to the track.

thank you for reading

mpetazzoni commented 11 months ago

Hi @strukturart,

The plugin does not expose an array of the LatLng points, as it also doesn't keep them internally – only temporarily to build the Leaflet.js Polyline. You can get them back from the Polyline layer object though.

Subscribe to the addline event: https://github.com/mpetazzoni/leaflet-gpx/blob/main/gpx.js#L575C5-L575C54

It will have a line attribute that is the L.Polyline object. You can the call getLatLngs() on that: https://leafletjs.com/reference.html#polyline-getlatlngs

HTH, Max

strukturart commented 11 months ago

Thank you for your answer, I found a way to get the data. probably with something detour but it works.

https://github.com/strukturart/o.map/blob/294b5754478447ae6dd6e1002436757fe1bc6a31/application/assets/js/module.js#L400

thanks for your plugin.

Clearmist commented 6 months ago

Working example

The async option must be true or your events won't be subscribed.

const gpxRoute = new L.GPX(gpx, { async: true })
  .on('addline', (event) => {
    console.log(event.line.getLatLngs());

    // Your code here.
  })
  .on('error', (e) => console.error(`Error loading gpx file: ${e.err}`))
  .addTo(map);

Result

An array of latitude and longitude objects.

[{
  "lat": 37.33547,
  "lng": -121.89207,
  "meta": {
    "time": "1970-01-01T08:00:00.000Z",
    "ele": 23.8,
    "hr": null,
    "cad": null,
    "atemp": null,
    "speed": 0
  }
}]