**Note: Server-side libraries**

> [!NOTE]
> This page describes the client-side service available with the Maps JavaScript API.
> If you want to work with Google Maps web services on your server, see the
> [Node.js Client for Google Maps Services](https://github.com/googlemaps/google-maps-services-js),
> [Java Client](https://github.com/googlemaps/google-maps-services-java),
> [Python Client](https://github.com/googlemaps/google-maps-services-python), and
> [Go Client for Google Maps Services](https://github.com/googlemaps/google-maps-services-go).

## Overview

> [!NOTE]
> Also see the Maps JavaScript API Reference: [Elevation](https://developers.google.com/maps/documentation/javascript/reference/elevation.md.txt)

The Elevation service provides elevation data for locations
on the surface of the earth, including depth locations on the
ocean floor (which return negative values). In those cases where
Google does not possess exact elevation measurements at the precise
location you request, the service will interpolate and return an
averaged value using the four nearest locations.

The `ElevationService` object provides you with
a simple interface to query locations on the earth for elevation
data. Additionally, you may request sampled elevation data along
paths, allowing you to calculate the equidistant elevation changes
along routes. The `ElevationService` object communicates
with the Google Maps API Elevation Service which receives elevation
requests and returns elevation data.

With the Elevation service, you can develop hiking and biking
applications, mobile positioning applications, or low resolution
surveying applications.

## Getting started

Before using the Elevation service in the Maps JavaScript API, first ensure
that the Elevation API is enabled in the Google Cloud console, in the same
project you set up for the Maps JavaScript API.

To view your list of enabled APIs:

1. Go to the [Google Cloud console](https://console.cloud.google.com/project/_/apiui/apis/enabled?utm_source=Docs_EnabledAPIsView).
2. Click the **Select a project** button, then select the same project you set up for the Maps JavaScript API and click **Open**.
3. From the list of APIs on the **Dashboard** , look for **Elevation API**.
4. If you see the API in the list, you're all set. If the API is *not* listed, enable it:
   1. At the top of the page, select **ENABLE API** to display the **Library** tab. Alternatively, from the left side menu, select **Library**.
   2. Search for **Elevation API**, then select it from the results list.
   3. Select **ENABLE** . When the process finishes, **Elevation API** appears in the list of APIs on the **Dashboard**.

## Pricing and policies

### Pricing

To learn about pricing and usage policies for the JavaScript Elevation service,
see [Usage and Billing](https://developers.google.com/maps/documentation/elevation/usage-and-billing.md.txt)
for the Elevation API.

### Policies

Use of the Elevation service must be in accordance with the
[policies described
for the Elevation API](https://developers.google.com/maps/documentation/elevation/policies).

## Elevation Requests

Accessing the Elevation service is asynchronous, since
the Google Maps API needs to make a call to an external
server. For that reason, you need to pass a *callback*
method to execute upon completion of the request. This
callback method should process the result(s). Note that the
Elevation service returns a status code
(`ElevationStatus`) and an array of separate
`ElevationResult` objects.

The `ElevationService` handles two types of requests:

- Requests for separate, discrete locations using the `getElevationForLocations()` method, which is passed a list of one or more locations using a `LocationElevationRequest` object.
- Requests for elevation on a series of connected points along a path using the `getElevationAlongPath()` method, which is passed an ordered set of path vertices within a `PathElevationRequest` object. When requesting elevations along paths, you must also pass a parameter indicating how many samples you wish to take along that path.

Each of these methods must also pass a *callback*
method to handle the returned `ElevationResult`
and `ElevationStatus` objects.

### Location Elevation Requests

A *`LocationElevationRequest`* object literal
contains the following field:

```javascript
{
  locations[]: LatLng
}
```

`locations` (required) defines the location(s) on the earth
from which to return elevation data. This parameter takes an array of
`LatLng`s.

You may pass any number of multiple coordinates within an array,
as long as you don't exceed the service quotas.
Note that when passing multiple coordinates, the
accuracy of any returned data may be of lower resolution than when
requesting data for a single coordinate.

### Sampled Path Elevation Requests

A *`PathElevationRequest`* object literal
contains the following fields:

```javascript
{
  path[]: LatLng,
  samples: Number
}
```

These fields are explained below:

- `path` (required) defines a path on the earth for which to return elevation data. The `path` parameter defines a set of two or more ordered {latitude,longitude} pairs using an array of two or more `LatLng` objects.
- `samples` (required) specifies the number of sample points along a path for which to return elevation data. The `samples` parameter divides the given `path` into an ordered set of equidistant points along the path.

As with positional requests, the `path` parameter
specifies a set of latitude and longitude values. Unlike a positional
request, however, the `path` specifies an ordered set of
vertices. Rather than return elevation data at the vertices, path
requests are sampled *along the length of the path*, where each
sample is equidistant from each other (inclusive of the endpoints).

## Elevation Responses

For each valid request, the Elevation service will return
to the defined callback a set of `ElevationResult`
objects along with an `ElevationStatus` object.

### Elevation Statuses

Each elevation request returns an `ElevationStatus` code
within its callback function. This `status` code
will contain one of the following values:

- `OK` indicating the service request was successful
- `INVALID_REQUEST` indicating the service request was malformed
- `OVER_QUERY_LIMIT` indicating that the requestor has exceeded quota
- `REQUEST_DENIED` indicating the service did not complete the request, likely because on an invalid parameter
- `UNKNOWN_ERROR` indicating an unknown error

You should check that your callback succeeded by examining this
status code for `OK`.

### Elevation Results

Upon success, the `results` argument of your callback
function will contain a set of `ElevationResult` objects.
These objects contain the following elements:

- A `location` element (containing `LatLng` objects) of the position for which elevation data is being computed. Note that for path requests, the set of `location` elements will contain the sampled points along the path.
- An `elevation` element indicating the elevation of the location in meters.
- A `resolution` value, indicating the maximum distance between data points from which the elevation was interpolated, in meters. This property will be missing if the resolution is not known. Note that elevation data becomes more coarse (larger `resolution` values) when multiple points are passed. To obtain the most accurate elevation value for a point, it should be queried independently.

## Elevation Examples

The following code translates a click on a map into an elevation
request using the `LocationElevationRequest` object:

### TypeScript

```typescript
async function init(): Promise<void> {
    const [{ InfoWindow }, { ElevationService }] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('elevation'),
    ]);

    const mapElement = document.querySelector('gmp-map')!;
    const innerMap = mapElement.innerMap;

    const elevator = new ElevationService();
    const infowindow = new InfoWindow();

    infowindow.open(innerMap);

    // Add a listener for the click event. Display the elevation for the LatLng of
    // the click inside the infowindow.
    innerMap.addListener('click', (event: google.maps.MapMouseEvent) => {
        displayLocationElevation(event.latLng!, elevator, infowindow, innerMap);
    });
}

function displayLocationElevation(
    location: google.maps.LatLng,
    elevator: google.maps.ElevationService,
    infowindow: google.maps.InfoWindow,
    map: google.maps.Map
) {
    // Format numeric values to two decimal places
    const formatter = new Intl.NumberFormat(undefined, {
        maximumFractionDigits: 2,
    });

    // Initiate the location request
    elevator
        .getElevationForLocations({
            locations: [location],
        })
        .then(({ results }) => {
            if (results[0]) {
                const { elevation, location: resultLocation } = results[0];
                infowindow.setPosition(resultLocation);
                infowindow.setContent(
                    `The elevation at ${String(resultLocation)} <br>is ${formatter.format(elevation)} meters.`
                );
            } else {
                infowindow.setPosition(location);
                infowindow.setContent('No results found');
            }

            infowindow.open(map);
        })
        .catch((e: unknown) => {
            infowindow.setContent(
                `Elevation service failed due to: ${String(e)}`
            );
        });
}

void init();
```

### JavaScript

```javascript
async function init() {
    const [{ InfoWindow }, { ElevationService }] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('elevation'),
    ]);

    const mapElement = document.querySelector('gmp-map');
    const innerMap = mapElement.innerMap;

    const elevator = new ElevationService();
    const infowindow = new InfoWindow();

    infowindow.open(innerMap);

    // Add a listener for the click event. Display the elevation for the LatLng of
    // the click inside the infowindow.
    innerMap.addListener('click', (event) => {
        displayLocationElevation(event.latLng, elevator, infowindow, innerMap);
    });
}

function displayLocationElevation(location, elevator, infowindow, map) {
    // Format numeric values to two decimal places
    const formatter = new Intl.NumberFormat(undefined, {
        maximumFractionDigits: 2,
    });

    // Initiate the location request
    elevator
        .getElevationForLocations({
            locations: [location],
        })
        .then(({ results }) => {
            if (results[0]) {
                const { elevation, location: resultLocation } = results[0];
                infowindow.setPosition(resultLocation);
                infowindow.setContent(
                    `The elevation at ${String(resultLocation)} <br>is ${formatter.format(elevation)} meters.`
                );
            } else {
                infowindow.setPosition(location);
                infowindow.setContent('No results found');
            }

            infowindow.open(map);
        })
        .catch((e) => {
            infowindow.setContent(
                `Elevation service failed due to: ${String(e)}`
            );
        });
}

void init();
```
[View example](https://developers.google.com/maps/documentation/javascript/examples/elevation-simple.md.txt)

### Try Sample

[JSFiddle.net](https://jsfiddle.net/gh/get/library/pure/googlemaps-samples/js-api-samples/tree/main/dist/samples/elevation-simple/jsfiddle)

The following example constructs a polyline given a set of coordinates
and displays elevation data along that path using the
[Google Visualization API](https://developers.google.com/chart). (You must load this API using the Google Common
Loader.) An elevation request is constructed using the
`PathElevationRequest`:

### TypeScript

```typescript
// Load the Visualization API and the columnchart package.
// @ts-ignore TODO 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,
    })
    .then(plotElevation)
    .catch((e) => {
      const chartDiv = document.getElementById(
        "elevation_chart"
      ) as HTMLElement;

      // Show the error code inside the chartDiv.
      chartDiv.innerHTML = "Cannot show elevation: request failed because " + e;
    });
}

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

  // 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 < results.length; i++) {
    data.addRow(["", results[i].elevation]);
  }

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

declare global {
  interface Window {
    initMap: () => void;
  }
}
window.initMap = initMap;
```

> [!NOTE]
> **Note:** Read the [guide](https://developers.google.com/maps/documentation/javascript/using-typescript.md.txt) on using TypeScript and Google Maps.

### JavaScript

```javascript
// Load the Visualization API and the columnchart package.
// @ts-ignore TODO update to newest visualization library
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 }, // 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"), {
    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,
    })
    .then(plotElevation)
    .catch((e) => {
      const chartDiv = document.getElementById("elevation_chart");

      // Show the error code inside the chartDiv.
      chartDiv.innerHTML = "Cannot show elevation: request failed because " + e;
    });
}

// Takes an array of ElevationResult objects, draws the path on the map
// and plots the elevation profile on a Visualization API ColumnChart.
function plotElevation({ results }) {
  const chartDiv = document.getElementById("elevation_chart");
  // 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 < results.length; i++) {
    data.addRow(["", results[i].elevation]);
  }

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

window.initMap = initMap;
```

> [!NOTE]
> **Note:** The JavaScript is compiled from the TypeScript snippet.

[View example](https://developers.google.com/maps/documentation/javascript/examples/elevation-paths.md.txt)