mpetazzoni / leaflet-gpx

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

Getting the Url of the loaded gpx #105

Closed DGrv closed 3 years ago

DGrv commented 3 years ago

Hi,

It is certainly an easy thing but I unfortunately do not find. I am try to get during the loading of a gpx the original url of it in order to let the user click on the gpx and download it if needed

With the code below I am actually trying to get in g.on('loaded', the original url from g ( loopinfo.what[j][i] ) and paste it in ???????????????

Could you help me ?

Thanks


for (var j = 0; j < loopinfo.what.length; j += 1) {
  for (var i = 0; i < loopinfo.what[j].length; i += 1) {

    var g = new L.GPX(loopinfo.what[j][i])

    g.on('loaded', function(e) {
      var gpx = e.target,
      namegpx = gpx.get_name(),
          distM = gpx.get_distance(),
          distKm = distM / 1000,
          distKmRnd = distKm.toFixed(1),
          eleGain = gpx.get_elevation_gain().toFixed(0),
          eleLoss = gpx.get_elevation_loss().toFixed(0),
          cen = gpx.getBounds().getCenter();
    var info = "Name: " + namegpx + "</br>" +
        "Distance: " + distKmRnd + " km </br>" +
        "Elevation Gain: " + eleGain + " m </br>" +
    "Elevation Loss: " + eleLoss + " m </br>" +
        "<a href='" + ??????????????? + "' target='_blank'>Link</a></br>" +
        "<a href='" + share + "' target='_blank'>Share location</a></br>";
        // register popup on click
        gpx.getLayers()[0].bindPopup(info);
    });

g.addTo(loopinfo.layer[j]);
mpetazzoni commented 3 years ago

The library doesn't have a way to get you back the URL of the GPX that was loaded, because it doesn't just take URLs as input (you can also directly pass GPX XML to the L.GPX(...) constructor). But since you already have that URL in your code, you don't need the library to give it back to you.

Your problem here is a classic Javascript callback scope capture problem. You can read more about this here: https://www.pluralsight.com/guides/javascript-callbacks-variable-scope-problem

You can make it work with this:

for (var j = 0; j < loopinfo.what.length; j += 1) {
  for (var i = 0; i < loopinfo.what[j].length; i += 1) {
    var url = loopinfo.what[j][i];
    new L.GPX(url).on('loaded', (function() {
      var _url = url;
      return function(e) {
        var gpx = e.target;
        var link = '<a href="' + _url + '">Link</a>';
        ...
      }
    })() );
  }
}
DGrv commented 3 years ago

Great thanks I got it work with your help 👍 and learned something important. Thanks for the references :)