leaflet – Display a Leaflet Heatmap with a GPX File and Omnivore

gpxheat mapleafletleaflet-plugins

I first displayed a Leaflet Heatmap with the plugin : "leaflet-heat.js" and a geojson file with this code found on Gis.Stackexchange

var geoJsonUrl = "link to the geojson file"

    var geojsonLayer = $.ajax({
    url : geoJsonUrl,
    dataType : 'json',
    jsonpCallback: 'getJson',
    });

geoJson2heat = function(geojson, intensity) {
        return geojson.features.map(function(feature) {
        return [parseFloat(feature.geometry.coordinates[1]), 
                parseFloat(feature.geometry.coordinates[0]), intensity];
        });
        };
    
$.when(geojsonLayer).done(function() {
        var punti_mappa = geoJson2heat(geojsonLayer.responseJSON, 4);
        var heatMap = L.heatLayer(punti_mappa,{ 
        minOpacity: 0.9,
        radius: 7,
        gradient: {
        0.02: 'blue',
        0.2: 'cyan',
        0.3: 'green',
        0.6: 'yellow',
        0.7: 'red'
    },
    blur: 15, 
        maxZoom: 13});
        map.addLayer(heatMap);
        }); 

Now I want to display a Leaflet Heatmap with a gpx file and the "omnivore.js" plugin. I displayed the points (markers) on the map with this code

var gpxUrl = "link gpx file"
var gpxlayer = omnivore.gpx(gpxUrl).addTo(map);

but I don't know how to adapt the rest with the url to display the heatmap ?

var geojsonLayer = $.ajax({
    url : ?
    dataType : 'json',
    jsonpCallback: 'getJson',
    });

Best Answer

You have to wait for the 'ready' event of omnivore.gpx call and then use .toGeoJSON method to get GeoJSON object from your gpxlayer. This you can than use as input to geoJson2heat call.

Relevant part of the code could then look something like this:

var gpxlayer = omnivore.gpx(gpxUrl)
  .on('ready', function() {
      var geoJSON = gpxlayer.toGeoJSON();
      var punti_mappa = geoJson2heat(geoJSON, 4);
      .
      .
      .
    })
  .addTo(map);