How to Sample Elevation Along a Route at a Fixed Interval

API or service
Routing API + Elevation API
Task
Route geometry → a point every N meters → elevation profile
Examples
URLJavaScriptAI
Difficulty
Intermediate
Time
12 min

Sample elevation along a route at a fixed interval

You want an elevation profile with one point every 100 m (or every 25 m, or every 10 m) along a route, for example to show it in a chart, find the steepest section, or compare routes in the same way. The Routing API can return elevation with details=elevation, but its points follow the route geometry: dense on curves, sparse on straight sections. This guide takes the route geometry, places points at a fixed distance along it, and gets their elevation from the Elevation API in one request.

The example is a bike ride in Golden, Colorado, from 1801 19th Street up Lookout Mountain Road to the Buffalo Bill Memorial Museum (987 1/2 Lookout Mountain Road, Golden, CO 80401): 7,513 m and about 430 m of climbing.

If spacing doesn't matter and you only need a chart, Create an elevation profile for a route with Routing API elevation details is enough.

Task flow: waypoints → Routing API route geometry → a point every N meters → Elevation API (≤ 1,000 points per request) → evenly spaced elevation profile.

Get the route geometry

Request the route as JSON. The geometry of the result is the line you will sample:

https://api.geoapify.com/v1/routing?waypoints=39.744567,-105.225152|39.733471,-105.238471&mode=bicycle&details=elevation&format=json&apiKey=YOUR_API_KEY

Reduced response:

{
  "results": [
    {
      "distance": 7513,
      "time": 2075.076,
      "legs": [
        {
          "distance": 7513,
          "elevation_range": [
            [0, 1801.2],
            [19.390098021671086, 1802.1695049010837],
            [26.80314885434324, 1802.5401574427171],
            [133.48873755515328, 1810.5690239214466]
          ]
        }
      ],
      "geometry": [
        [
          { "lon": -105.225192, "lat": 39.744609 },
          { "lon": -105.225375, "lat": 39.744506 },
          { "lon": -105.225424, "lat": 39.744561 }
        ]
      ]
    }
  ]
}

details=elevation is added here only to show why you'd resample. For this route, elevation_range has 589 points, one per geometry point. The gap between neighbours ranges from 1.3 m to 114 m (median 9.7 m): the first entries above are 19 m, 7 m and 107 m apart. You don't need details=elevation for the rest of this guide.

With format=json, geometry is an array per leg of { lon, lat } objects. With the default GeoJSON format, the same line is in features[0].geometry.coordinates as [longitude, latitude] pairs.

Choose the interval

One Elevation API request takes up to 1,000 locations and costs max(1, ceil(locations / 100)) credits. The number of points is about route length / interval + 1, so the interval sets both the detail and the cost.

The 7,505 m route line from the previous step, sampled live on November 17, 2026:

Interval Points Requests Credits Lowest / highest Total ascent
100 m 77 1 1 1,801 / 2,228 m 427 m
25 m 302 1 4 1,801 / 2,229 m 444 m
10 m 752 1 8 1,801 / 2,230 m 462 m
5 m 1,502 — — (HTTP 400)

Total ascent is the sum of every rise between neighbouring points. It grows with denser sampling because short ups and downs that a 100 m interval steps over are counted too.

More than 1,000 points in one request returns HTTP 400:

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "\"locations\" must contain less than or equal to 1000 items"
}

To keep a route in one request, use an interval of at least route length / 999: 7.6 m for this route, 50 m for a 50 km ride. For finer sampling, split the points into chunks of up to 1,000 and send one request per chunk.

Place a point every N meters

Walk along the route line, measure each segment, and add a point each time the distance traveled reaches the next multiple of the interval. Always keep the first and the last point of the route:

function haversine([lon1, lat1], [lon2, lat2]) {
  const R = 6371008.8;
  const rad = degrees => degrees * Math.PI / 180;
  const dLat = rad(lat2 - lat1);
  const dLon = rad(lon2 - lon1);
  const a = Math.sin(dLat / 2) ** 2
    + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLon / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(a));
}

// coords: [[lon, lat], ...] in route order; interval in meters
function samplePoints(coords, interval) {
  if (!Number.isFinite(interval) || interval <= 0) {
    throw new RangeError("interval must be a positive number of meters");
  }
  if (coords.length === 0) return [];

  const points = [{ location: coords[0], distance: 0 }];
  let traveled = 0;
  let next = interval;

  for (let i = 1; i < coords.length; i++) {
    const [a, b] = [coords[i - 1], coords[i]];
    const segment = haversine(a, b);

    while (segment > 0 && traveled + segment >= next) {
      const t = (next - traveled) / segment;
      points.push({
        location: [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t],
        distance: next
      });
      next += interval;
    }
    traveled += segment;
  }

  const last = coords[coords.length - 1];
  const remainder = traveled - points[points.length - 1].distance;
  if (points.length > 1 && remainder <= 1) {
    // Avoid a final section of 1 m or less: move the last sample to the route end
    points[points.length - 1] = { location: last, distance: traveled };
  } else if (remainder > 0) {
    points.push({ location: last, distance: traveled });
  }
  return points;
}

const route = routingResponse.results[0];
const coords = route.geometry.flat().map(({ lon, lat }) => [lon, lat]);
const points = samplePoints(coords, 100);

The function rejects an interval that is not a finite number greater than zero. If the route ends 1 m or less after a sampled point, that point moves to the end of the route instead of adding a very short final section.

route.geometry.flat() joins the legs of a multi-stop route into one line. Each point keeps distance, its position along the route in meters, which becomes the x-axis of the profile. Linear interpolation between two geometry points is accurate enough at these distances.

For the example route and a 100 m interval, points has 77 entries: 0, 100, 200 … 7,500 m, and the end of the route at 7,505 m.

Get the elevation of the points

Send the points as [longitude, latitude] arrays in the locations of one POST request:

POST https://api.geoapify.com/v1/geodata/elevation?apiKey=YOUR_API_KEY
Content-Type: application/json
{
  "locations": [
    [-105.225192, 39.744609],
    [-105.226121, 39.744179],
    [-105.227038, 39.743623],
    [-105.238274, 39.733609]
  ]
}

The request body above is reduced to the first three and the last of 77 points. Reduced response:

{
  "results": [
    { "location": { "lon": -105.225192, "lat": 39.744609 }, "elevation": 1801, "units": "m" },
    { "location": { "lon": -105.226121, "lat": 39.744179 }, "elevation": 1808, "units": "m" },
    { "location": { "lon": -105.227038, "lat": 39.743623 }, "elevation": 1816, "units": "m" },
    { "location": { "lon": -105.238274, "lat": 39.733609 }, "elevation": 2226, "units": "m" }
  ]
}

Results come back in the order of locations, so join them with the sampled points by index. This function also splits more than 1,000 points into several requests:

async function getProfile(points, apiKey) {
  const url = `https://api.geoapify.com/v1/geodata/elevation?apiKey=${apiKey}`;
  const profile = [];

  for (let start = 0; start < points.length; start += 1000) {
    const chunk = points.slice(start, start + 1000);
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ locations: chunk.map(point => point.location) })
    });
    if (!response.ok) {
      throw new Error((await response.json()).message);
    }
    const { results } = await response.json();
    results.forEach((result, i) => profile.push({
      distance: chunk[i].distance,
      elevation: result.elevation
    }));
  }
  return profile.filter(point => point.elevation !== null);
}

const profile = await getProfile(points, "YOUR_API_KEY");

elevation is null where no data is available, so the last line drops those points. Add "units": "imperial" to the body to get feet instead of meters; the sampled distances stay in meters until you convert them.

profile is a list of { distance, elevation } pairs: for the example, 1,801 m at 0 m, 1,808 m at 100 m, 1,816 m at 200 m, and so on to 2,226 m at 7,505 m. It works with the chart renderer from Render the elevation profile. Most sections are one interval long, but the final section is usually shorter and a dropped null point leaves a longer one, so divide by the distance between the two points rather than by the interval: the grade of each section is (elevation[i] − elevation[i−1]) / (distance[i] − distance[i−1]). The steepest 100 m of this ride is 10% at about 2.8 km.

Fixed-interval elevation profile with an AI coding agent

Copy this prompt into Codex, Claude Code, Cursor, or another coding agent to add an evenly sampled route elevation profile to your project.

Add an elevation profile with a fixed sampling interval to my project, using the Geoapify Routing API and Elevation API.

Before you start
- Inspect the existing project first. Reuse its current framework, HTTP client, map and chart libraries, and conventions. Make the smallest necessary changes.
- Ask only what the project does not answer: where the route comes from (an existing Routing API response or new waypoints), the travel mode, the interval in meters, and whether requests run in a backend or use a restricted browser API key.
- Read the Geoapify API key from the project's environment configuration. Never hardcode, print, or log it.

Route geometry
- If there is no route yet: GET https://api.geoapify.com/v1/routing?waypoints=lat,lon|lat,lon&mode=...&format=json&apiKey=...
- Use results[0].geometry (one array of {lon, lat} per leg), flattened into one line of [lon, lat] pairs in order. For GeoJSON responses use features[0].geometry.coordinates.

Sampling
- Walk the line with the haversine distance, add an interpolated point every N meters, always keep the first and the last point, and keep each point's distance along the route.
- Points per request: at most 1,000. Cost per request: max(1, ceil(locations / 100)) credits. Show the point count and the credit estimate before sending.

Elevation API
- POST https://api.geoapify.com/v1/geodata/elevation?apiKey=... with JSON { "locations": [[lon, lat], ...] } and optional "units": "imperial".
- Split more than 1,000 points into chunks of up to 1,000, one request each, and join results to points by index (results keep the input order).
- results[i].elevation can be null: skip those points.
- Use the distance along the route from the sampling step for the x-axis.

Errors
- Show the API message for HTTP 400 responses, and retry 429 responses a limited number of times with backoff.
- Add a test for the sampler: a straight two-point line of 250 m with a 100 m interval must give points at 0, 100, 200 and 250 m.

Review the generated code against this guide. Check the coordinate order ([longitude, latitude]), that the last point of the route is kept, the 1,000-location split, and the API-key handling.