Showing Elevation Along a Path

This example displays a graph that shows the elevation along a path drawn on the map.

Read the documentation.

TypeScript

// Load the Visualization API and the columnchart package.
// @ts-ignore TODO(jpoehnelt) update to newest visualization library
google.load("visualization", "1", { packages: ["columnchart"] });

function initMap(): void {
  // The following path marks a path from Mt. Whitney, the highest point in the
  // continental United States to Badwater, Death Valley, the lowest point.
  const path = [
    { lat: 36.579, lng: -118.292 }, // Mt. Whitney
    { lat: 36.606, lng: -118.0638 }, // Lone Pine
    { lat: 36.433, lng: -117.951 }, // Owens Lake
    { lat: 36.588, lng: -116.943 }, // Beatty Junction
    { lat: 36.34, lng: -117.468 }, // Panama Mint Springs
    { lat: 36.24, lng: -116.832 },
  ]; // Badwater, Death Valley

  const map = new google.maps.Map(
    document.getElementById("map") as HTMLElement,
    {
      zoom: 8,
      center: path[1],
      mapTypeId: "terrain",
    }
  );

  // Create an ElevationService.
  const elevator = new google.maps.ElevationService();

  // Draw the path, using the Visualization API and the Elevation service.
  displayPathElevation(path, elevator, map);
}

function displayPathElevation(
  path: google.maps.LatLngLiteral[],
  elevator: google.maps.ElevationService,
  map: google.maps.Map
) {
  // Display a polyline of the elevation path.
  new google.maps.Polyline({
    path: path,
    strokeColor: "#0000CC",
    strokeOpacity: 0.4,
    map: map,
  });

  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  // Initiate the path request.
  elevator.getElevationAlongPath(
    {
      path: path,
      samples: 256,
    },
    plotElevation
  );
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(elevations, status) {
  const chartDiv = document.getElementById("elevation_chart") as HTMLElement;

  if (status !== "OK") {
    // Show the error code inside the chartDiv.
    chartDiv.innerHTML =
      "Cannot show elevation: request failed because " + status;
    return;
  }
  // Create a new chart in the elevation_chart DIV.
  const chart = new google.visualization.ColumnChart(chartDiv);

  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  const data = new google.visualization.DataTable();
  data.addColumn("string", "Sample");
  data.addColumn("number", "Elevation");

  for (let i = 0; i < elevations.length; i++) {
    data.addRow(["", elevations[i].elevation]);
  }

  // Draw the chart using the data within its DIV.
  chart.draw(data, {
    height: 150,
    legend: "none",
    // @ts-ignore TODO(jpoehnelt) update to newest visualization library
    titleY: "Elevation (m)",
  });
}

JavaScript

// Load the Visualization API and the columnchart package.
google.load("visualization", "1", { packages: ["columnchart"] });

function initMap() {
  // The following path marks a path from Mt. Whitney, the highest point in the
  // continental United States to Badwater, Death Valley, the lowest point.
  const path = [
    { lat: 36.579, lng: -118.292 },
    { lat: 36.606, lng: -118.0638 },
    { lat: 36.433, lng: -117.951 },
    { lat: 36.588, lng: -116.943 },
    { lat: 36.34, lng: -117.468 },
    { lat: 36.24, lng: -116.832 },
  ]; // Badwater, Death Valley
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 8,
    center: path[1],
    mapTypeId: "terrain",
  });
  // Create an ElevationService.
  const elevator = new google.maps.ElevationService();
  // Draw the path, using the Visualization API and the Elevation service.
  displayPathElevation(path, elevator, map);
}

function displayPathElevation(path, elevator, map) {
  // Display a polyline of the elevation path.
  new google.maps.Polyline({
    path: path,
    strokeColor: "#0000CC",
    strokeOpacity: 0.4,
    map: map,
  });
  // Create a PathElevationRequest object using this array.
  // Ask for 256 samples along that path.
  // Initiate the path request.
  elevator.getElevationAlongPath(
    {
      path: path,
      samples: 256,
    },
    plotElevation
  );
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation(elevations, status) {
  const chartDiv = document.getElementById("elevation_chart");

  if (status !== "OK") {
    // Show the error code inside the chartDiv.
    chartDiv.innerHTML =
      "Cannot show elevation: request failed because " + status;
    return;
  }
  // Create a new chart in the elevation_chart DIV.
  const chart = new google.visualization.ColumnChart(chartDiv);
  // Extract the data from which to populate the chart.
  // Because the samples are equidistant, the 'Sample'
  // column here does double duty as distance along the
  // X axis.
  const data = new google.visualization.DataTable();
  data.addColumn("string", "Sample");
  data.addColumn("number", "Elevation");

  for (let i = 0; i < elevations.length; i++) {
    data.addRow(["", elevations[i].elevation]);
  }
  // Draw the chart using the data within its DIV.
  chart.draw(data, {
    height: 150,
    legend: "none",
    titleY: "Elevation (m)",
  });
}

CSS

/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
#map {
  height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

HTML

<!DOCTYPE html>
<html>
  <head>
    <title>Showing Elevation Along a Path</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script src="https://www.google.com/jsapi"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script src="./index.js"></script>
  </head>
  <body>
    <div>
      <div id="map" style="height: 250px"></div>
      <div id="elevation_chart"></div>
    </div>
  </body>
</html>

All

<!DOCTYPE html>
<html>
  <head>
    <title>Showing Elevation Along a Path</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <script src="https://www.google.com/jsapi"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
      defer
    ></script>
    <style type="text/css">
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }

      /* Optional: Makes the sample page fill the window. */
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <script>
      // Load the Visualization API and the columnchart package.
      google.load("visualization", "1", { packages: ["columnchart"] });

      function initMap() {
        // The following path marks a path from Mt. Whitney, the highest point in the
        // continental United States to Badwater, Death Valley, the lowest point.
        const path = [
          { lat: 36.579, lng: -118.292 },
          { lat: 36.606, lng: -118.0638 },
          { lat: 36.433, lng: -117.951 },
          { lat: 36.588, lng: -116.943 },
          { lat: 36.34, lng: -117.468 },
          { lat: 36.24, lng: -116.832 },
        ]; // Badwater, Death Valley
        const map = new google.maps.Map(document.getElementById("map"), {
          zoom: 8,
          center: path[1],
          mapTypeId: "terrain",
        });
        // Create an ElevationService.
        const elevator = new google.maps.ElevationService();
        // Draw the path, using the Visualization API and the Elevation service.
        displayPathElevation(path, elevator, map);
      }

      function displayPathElevation(path, elevator, map) {
        // Display a polyline of the elevation path.
        new google.maps.Polyline({
          path: path,
          strokeColor: "#0000CC",
          strokeOpacity: 0.4,
          map: map,
        });
        // Create a PathElevationRequest object using this array.
        // Ask for 256 samples along that path.
        // Initiate the path request.
        elevator.getElevationAlongPath(
          {
            path: path,
            samples: 256,
          },
          plotElevation
        );
      }

      // Takes an array of ElevationResult objects, draws the path on the map
      // and plots the elevation profile on a Visualization API ColumnChart.
      function plotElevation(elevations, status) {
        const chartDiv = document.getElementById("elevation_chart");

        if (status !== "OK") {
          // Show the error code inside the chartDiv.
          chartDiv.innerHTML =
            "Cannot show elevation: request failed because " + status;
          return;
        }
        // Create a new chart in the elevation_chart DIV.
        const chart = new google.visualization.ColumnChart(chartDiv);
        // Extract the data from which to populate the chart.
        // Because the samples are equidistant, the 'Sample'
        // column here does double duty as distance along the
        // X axis.
        const data = new google.visualization.DataTable();
        data.addColumn("string", "Sample");
        data.addColumn("number", "Elevation");

        for (let i = 0; i < elevations.length; i++) {
          data.addRow(["", elevations[i].elevation]);
        }
        // Draw the chart using the data within its DIV.
        chart.draw(data, {
          height: 150,
          legend: "none",
          titleY: "Elevation (m)",
        });
      }
    </script>
  </head>
  <body>
    <div>
      <div id="map" style="height: 250px"></div>
      <div id="elevation_chart"></div>
    </div>
  </body>
</html>
// Load the Visualization API and the columnchart package. google.load("visualization", "1", { packages: ["columnchart"] }); function initMap() { // The following path marks a path from Mt. Whitney, the highest point in the // continental United States to Badwater, Death Valley, the lowest point. const path = [ { lat: 36.579, lng: -118.292 }, { lat: 36.606, lng: -118.0638 }, { lat: 36.433, lng: -117.951 }, { lat: 36.588, lng: -116.943 }, { lat: 36.34, lng: -117.468 }, { lat: 36.24, lng: -116.832 }, ]; // Badwater, Death Valley const map = new google.maps.Map(document.getElementById("map"), { zoom: 8, center: path[1], mapTypeId: "terrain", }); // Create an ElevationService. const elevator = new google.maps.ElevationService(); // Draw the path, using the Visualization API and the Elevation service. displayPathElevation(path, elevator, map); } function displayPathElevation(path, elevator, map) { // Display a polyline of the elevation path. new google.maps.Polyline({ path: path, strokeColor: "#0000CC", strokeOpacity: 0.4, map: map, }); // Create a PathElevationRequest object using this array. // Ask for 256 samples along that path. // Initiate the path request. elevator.getElevationAlongPath( { path: path, samples: 256, }, plotElevation ); } // Takes an array of ElevationResult objects, draws the path on the map // and plots the elevation profile on a Visualization API ColumnChart. function plotElevation(elevations, status) { const chartDiv = document.getElementById("elevation_chart"); if (status !== "OK") { // Show the error code inside the chartDiv. chartDiv.innerHTML = "Cannot show elevation: request failed because " + status; return; } // Create a new chart in the elevation_chart DIV. const chart = new google.visualization.ColumnChart(chartDiv); // Extract the data from which to populate the chart. // Because the samples are equidistant, the 'Sample' // column here does double duty as distance along the // X axis. const data = new google.visualization.DataTable(); data.addColumn("string", "Sample"); data.addColumn("number", "Elevation"); for (let i = 0; i < elevations.length; i++) { data.addRow(["", elevations[i].elevation]); } // Draw the chart using the data within its DIV. chart.draw(data, { height: 150, legend: "none", titleY: "Elevation (m)", }); }
/* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map { height: 100%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
<!DOCTYPE html> <html> <head> <title>Showing Elevation Along a Path</title> <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script> <script src="https://www.google.com/jsapi"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBIwzALxUPNbatRBj3Xi1Uhp0fFzwWNBkE&callback=initMap&libraries=&v=weekly" defer ></script> <!-- jsFiddle will insert css and js --> </head> <body> <div> <div id="map" style="height: 250px"></div> <div id="elevation_chart"></div> </div> </body> </html>

Create a starter application from sample

A skeleton starter application using TypeScript, Webpack, and Babel can be generated from this sample using one of the methods below.

Run Locally

Node.js is required to run this sample locally. Follow these instructions to install Node.js and NPM.

npx @googlemaps/js-samples init elevation-paths DESTINATION_FOLDER

Run in Google Cloud Shell

Google Cloud Shell is an interactive shell environment for Google Cloud Platform that makes it easy for you to learn and experiment with GCP and manage your projects and resources from your web browser.

Run in Cloud Shell