Route Elevation Profile with Chart.js

This code sample shows you how to calculate a route with the Geoapify Routing API and visualize the elevation profile of that route with Chart.js.

by Geoapify

HTML

<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/maplibre-gl.css">
<script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<div id="my-map"></div>
<div class="elevation-profile-container">
  <canvas id="route-elevation-chart" style="width:100%;height:100%"></canvas>
</div>

CSS

html,
body {
  margin: 0;
  padding: 0;

  height: 100%;
  display: flex;
  flex-direction: column;
}

#my-map {
  flex: 1;
}

.elevation-profile-container {
  height: 250px;
}

JavaScript

Chart.register(
  Chart.LineElement,
  Chart.LineController,
  Chart.Legend,
  Chart.Tooltip,
  Chart.LinearScale,
  Chart.PointElement,
  Chart.Filler,
  Chart.Title
);

// The API Key provided is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
const myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";

const map = new maplibregl.Map({
  container: 'my-map',
  style: `https://maps.geoapify.com/v1/styles/osm-carto/style.json?apiKey=${myAPIKey}`,
  center: [-110.63886603832373, 44.57344946153063],
  zoom: 8
});
map.addControl(new maplibregl.NavigationControl());

const popup = new maplibregl.Popup();

const waypoints = [{
    latlon: [44.56887641018278, -110.37193509232105],
    address: "Howard Eaton-Fishing Bridge-Canyon, Park County, WY, United States of America"
  },
  {
    latlon: [44.64991504629589, -110.87685585784652],
    address: "251 Echo Canyon Road, Teton County, WY, United States of America"
  },
  {
    latlon: [44.46198969253814, -110.83290070191913],
    address: "Lower Hamilton Store, 251 Echo Canyon Road, Teton County, WY, United States of America"
  },
  {
    latlon: [44.534340496926745, -110.43392313273148],
    address: "Grand Loop Road, Bridge Bay, WY, United States of America"
  }
]

// create markers
const markers = [];
waypoints.forEach(waypoint => {
  markers.push(new maplibregl.Marker().setLngLat([waypoint.latlon[1], waypoint.latlon[0]])
    .setPopup(new maplibregl.Popup().setText(waypoint.address)).addTo(map));
});

let routeData;
let elevationData;

fetch(`https://api.geoapify.com/v1/routing?waypoints=${waypoints.map(waypoint => waypoint.latlon.join(',')).join('|')}&mode=mountain_bike&details=elevation&apiKey=${myAPIKey}`).then(res => res.json()).then(routeResult => {
  routeData = routeResult;
  elevationData = calculateElevationProfileData(routeResult);

  map.addSource('route', {
    type: 'geojson',
    data: routeData
  });

  drawRoute();
  drawElevationProfile();
}, err =>...