[GIS] Load multiple GPX files to Leaflet map

gpxleaflet

Considering I have a folder that contains multiple .gpx tracks, my objective is to show each of them in a single leaflet map. Then I would personalize thing like tooltips of each track, the color for each track, etc.

I already searched and found these libraries:

https://github.com/mapbox/leaflet-omnivore

https://github.com/mpetazzoni/leaflet-gpx

But they only let me load one track. Is there a way to load an entire folder?

If leaflet does not allow it, is there another option?

EDIT:

So I have the tracks folder on my backend/server side, so to read them at the frontend I need some way to get the data.

My backend runs using Flask, and I got an endpoint to list all the files:

class GPS_Tracks(Resource):
  def get(self):
      files =[]
      for f in os.listdir(files_directory):
        if f.endswith(".gpx"):
          files.append(f)
      files.sort()
      return files

It returns something like this:

[
    "2016-01-15 17-43-20.gpx", 
    "2016-01-15 18-34-15.gpx", 
    "2016-01-16 21-36-19.gpx", 
    "2016-01-16 21-48-17.gpx", 
    "2016-01-16 22-58-56.gpx",
...]

So my frontend does a request to that endpoint and gets the names of the files. But I need to still access the files.

Best Answer

EDIT 2 following rev 3 of the question

There is nothing wrong in using a 2-steps approach:

  1. Make a 1st AJAX request to retrieve the list of files paths to be loaded.
  2. Make a bunch of AJAX requests to load each file individually (possibly through omnivore).

Note that you need the exact file path, whereas in your code you seem to send only the file name.

If all your files are in the same folder, and that folder never changes, then you can hard-code its path in your client script and infer the files full path: omnivore.gpx(folderPath + listOfFilesNames[i])


EDIT following below comments

If you can have a hard-coded list of your server files paths as a JavaScript array, then it is trivial to use the code in the original answer:

var listOfFilesPath = [
  "path/to/file1.gpx",
  "path/to/file2.gpx",
  "path/to/file3.gpx" // etc.
];

Now if you do not have that hard-coded list, you will have to find a way to generate it server side, as the client (browser) cannot list by itself all files in a server folder. Unless you use a predefined template for their paths and blindly generate those paths in your client script.


Original answer:

You can load as many files as you wish, as long as you can list them:

for (var i = 0; i < listOfFilesPath.length; i += 1) {
  omnivore.gpx(listOfFilesPath[i]).addTo(map);
}