DEV Community

Cover image for Same 22 km, 11 Minutes Apart: Map Drive Times from Many Places at Once
Casey Rivers for Geoapify Maps API

Posted on

Same 22 km, 11 Minutes Apart: Map Drive Times from Many Places at Once

Centennial and Highlands Ranch are both about 22 km from Denver Union Station in a straight line. By car, one is 19 minutes away and the other 30.

"How long does it take to get here from everywhere around?" is the question behind choosing an office, a warehouse, a store or a meeting place. In this tutorial we answer it for every town around Denver with one API request, color each town by its minutes on a map, and draw the route when you click one. At the end, we ask an AI coding assistant to build the same page.

TL;DR

  • The Route Matrix API takes many sources and one target in a single POST and returns the drive time and distance for each pair.
  • One request takes up to 1,000 pairs: with one destination, up to 1,000 places. Around Denver, 31, 56 and 347 places each took one request.
  • Straight-line distance is a poor guess: places 22 km away are 19 or 30 minutes away by car.
  • Cost: max(sources, targets) × min(sources, targets, 10) credits, so 31 places to one destination cost 31 credits. The Free plan has 3,000 credits a day.
  • The origins come from the Places API (cities, towns, suburbs, neighbourhoods), and a click on a dot draws its route with the Routing API.
  • An AI assistant got the matrix request right from a vague prompt, but typed 20 town coordinates from memory and painted most of the map one color. A precise prompt got our demo.

👉 Live demo: click a dot for its route, click the map to move the destination, or add more places.


Table of Contents

  1. Why straight-line distance misleads
  2. How many places fit in one request?
  3. Where should the meeting be?
  4. Step 1: Load the places
  5. Step 2: One request for every drive time
  6. Step 3: Color the dots by minutes
  7. Step 4: Draw the route of a clicked place
  8. Let an AI assistant write it
  9. Summary
  10. FAQ

Why straight-line distance misleads

A circle around a destination is the quickest answer to "what's close?". It treats every direction the same, and roads don't.

Map of the Denver area with a dashed 22 km circle around Denver Union Station. Centennial, on the circle to the south-east, is 19 minutes away by car via I-25; Highlands Ranch, on the circle to the south, is 30 minutes away on a route that first runs east to I-25

Centennial sits next to I-25, so its 27 km by road go fast. From Highlands Ranch, the fastest route first runs east to I-25: 43 km by road for 22.7 km as the crow flies. A few more places, all driving to Union Station:

Place Straight line By road Drive time
Lakewood 8.7 km 13.0 km 11 min
Arvada 8.7 km 14.5 km 14 min
Golden 18.8 km 25.6 km 19 min
Columbine 19.3 km 28.3 km 27 min
Centennial 22.0 km 27.1 km 19 min
Highlands Ranch 22.7 km 43.3 km 30 min

Drive times from the Route Matrix API, mode=drive, default traffic=free_flow (no traffic jams). Straight lines measured between the same coordinates.

How many places fit in one request?

A matrix request takes a list of sources and a list of targets and returns every pair. With one target, the list of sources can be long: one request takes up to 1,000 pairs.

Three maps of the Denver area at the same scale, each with dots colored by drive time to Union Station: 31 cities and towns, 56 places with villages and suburbs, and 347 places with neighbourhoods. Each map is labeled "1 request" with its credits: 31, 56 and 347

Places within 40 km Places API categories Sources Matrix credits Response time
Cities and towns city, town 31 31 ~3 s
+ villages and suburbs + village, suburb 56 56 ~3 s
+ neighbourhoods + neighbourhood 347 347 ~15 s

The median stays at 21 minutes in all three, but the details change: with neighbourhoods, 99 of 347 places are within 15 minutes of Union Station, and the slowest is 56 minutes away in the foothills. One of the 347 gets no route at all: its cell comes back as null.

Where should the meeting be?

Move the destination, and the same 56 places tell a different story. This is the question a matrix answers best: which location is closest for most people?

Three maps of the same 56 places around Denver, colored by drive time to three different destinations: Denver Union Station with 14 places within 15 minutes, the Denver Tech Center with 12, and Southlands in Aurora with 3

Destination Within 15 min Within 20 min Median
Denver Union Station 14 of 56 25 21 min
Belmar, Lakewood 14 of 56 22 22 min
Denver Tech Center 12 of 56 20 24 min
Interlocken, Broomfield 9 of 56 17 28 min
Southlands, Aurora 3 of 56 7 31 min

Each row is one matrix request: 56 places, one destination.

Step 1: Load the places

Any list of coordinates works as origins: customers, employees, stores. The demo takes populated places from the Places API, so the map shows real towns and neighbourhoods.

const categories = [
  "populated_place.city",
  "populated_place.town",
  // add "populated_place.village", "populated_place.suburb", "populated_place.neighbourhood" for more
].join(",");

const url = `https://api.geoapify.com/v2/places?categories=${categories}` +
  `&filter=circle:-104.99,39.74,40000` + // lon, lat, radius in meters
  `&limit=500&apiKey=YOUR_API_KEY`;

const places = await (await fetch(url)).json();
const origins = places.features.map((feature) => ({
  name: feature.properties.name,
  lon: feature.geometry.coordinates[0],
  lat: feature.geometry.coordinates[1],
}));
Enter fullscreen mode Exit fullscreen mode
Parameter Value Why
categories populated_place.city,… Cities and towns; more categories add more places
filter circle:lon,lat,meters Places within 40 km of central Denver
limit 500 The default is 20; 500 is the maximum per page

Every 20 places cost 1 credit, so 31 places cost 2 credits.

Step 2: One request for every drive time

All origins go into sources, the destination is the only target. Coordinates are [longitude, latitude].

const response = await fetch("https://api.geoapify.com/v1/routematrix?apiKey=YOUR_API_KEY", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    mode: "drive",
    sources: origins.map((origin) => ({ location: [origin.lon, origin.lat] })),
    targets: [{ location: [-105.0003, 39.7527] }], // Denver Union Station
  }),
});
const result = await response.json();

// One row per source, one cell per target.
// time is in seconds, distance in meters; both are null when there is no route.
const cells = result.sources_to_targets.map((row) => row[0]);
Enter fullscreen mode Exit fullscreen mode

A reduced response for two sources, Arvada and a neighbourhood with no route:

{
  "sources_to_targets": [
    [{ "distance": 14477, "time": 826, "source_index": 0, "target_index": 0 }],
    [{ "distance": null, "time": null, "source_index": 1, "target_index": 0 }]
  ],
  "units": "metric",
  "distance_units": "meters",
  "mode": "drive"
}
Enter fullscreen mode Exit fullscreen mode
  • Order: cell i belongs to sources[i]. Keep your origins array in the same order.
  • No route: a point far from any road gets null. Check before dividing by 60.
  • Direction: this is the time to the destination. Times from the destination can differ (one-way streets, ramps), so swap sources and targets for the other direction.
  • Traffic: the default traffic=free_flow assumes empty roads. traffic=approximated slows down roads that are usually busy.
  • More than 1,000 pairs: split the sources into several requests.

Step 3: Color the dots by minutes

Store the color in each feature, and one circle layer plus one symbol layer draw all places.

// Color stops in minutes: green → yellow → dark red at 30+
const STOPS = [[0, [26, 152, 80]], [10, [145, 207, 96]], [15, [254, 224, 139]],
               [20, [252, 141, 89]], [25, [215, 48, 39]], [30, [127, 0, 0]]];

function colorForMinutes(minutes) {
  const value = Math.min(minutes, 30);
  for (let i = 1; i < STOPS.length; i++) {
    const [toMin, toRgb] = STOPS[i];
    const [fromMin, fromRgb] = STOPS[i - 1];
    if (value <= toMin) {
      const t = (value - fromMin) / (toMin - fromMin);
      return `rgb(${fromRgb.map((c, j) => Math.round(c + (toRgb[j] - c) * t)).join(",")})`;
    }
  }
}

const features = origins.map((origin, i) => {
  const minutes = cells[i].time === null ? null : Math.round(cells[i].time / 60);
  return {
    type: "Feature",
    geometry: { type: "Point", coordinates: [origin.lon, origin.lat] },
    properties: {
      label: minutes === null ? "–" : String(minutes),
      color: minutes === null ? "#52606d" : colorForMinutes(minutes),
    },
  };
});
map.getSource("origins").setData({ type: "FeatureCollection", features });

map.addLayer({
  id: "origin-circles",
  type: "circle",
  source: "origins",
  paint: { "circle-radius": 12, "circle-color": ["get", "color"], "circle-stroke-color": "#fff", "circle-stroke-width": 1.5 },
});
map.addLayer({
  id: "origin-labels",
  type: "symbol",
  source: "origins",
  layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Bold"], "text-size": 11 },
  paint: { "text-color": "#fff" },
});
Enter fullscreen mode Exit fullscreen mode

Map of the Denver area with 31 cities and towns as dots, each labeled with its drive time in minutes to Denver Union Station: 6 minutes next to downtown, 10 to 15 in the inner suburbs, 25 to 37 at the edges, and a green-to-red legend

Noto Sans Bold is one of the fonts of the Geoapify map styles. With hundreds of places, the demo makes the dots smaller and drops the labels; the minutes show on hover.

Step 4: Draw the route of a clicked place

A matrix gives numbers, not lines. To show how a place gets there, ask the Routing API for that one route when its dot is clicked.

map.on("click", async (event) => {
  const [dot] = map.queryRenderedFeatures(event.point, { layers: ["origin-circles"] });
  if (!dot) return; // a click on the empty map moves the destination in the demo

  const [lon, lat] = dot.geometry.coordinates;
  const waypoints = `${lat},${lon}|39.7527,-105.0003`; // lat,lon here, unlike the matrix
  const route = await (await fetch(
    `https://api.geoapify.com/v1/routing?waypoints=${waypoints}&mode=drive&apiKey=YOUR_API_KEY`
  )).json();

  map.getSource("route").setData(route); // a GeoJSON FeatureCollection
  const { time, distance } = route.features[0].properties; // seconds, meters
});
Enter fullscreen mode Exit fullscreen mode

Map with a dark route line from Arvada to Denver Union Station and the colored dots of nearby towns; a box reads "Click Arvada: 14 min, 14.5 km, the Routing API route matches the matrix cell"

The route for Arvada is 14 minutes and 14.5 km, the same as its matrix cell. One route costs 1 credit, so draw routes on demand instead of for every place.

Let an AI assistant write it

We gave the task to an AI coding assistant (Claude) twice, each time in a fresh session without web access, and ran both pages with a real API key.

Prompt 1, vague:

Using the Geoapify API, make a web page that shows on a map how long it takes to drive to Denver Union Station from the towns around Denver. One HTML file please.

Page written by an AI assistant from the vague prompt: a MapLibre map of the Denver area with 20 town labels such as "Lakewood 11'", "Boulder 30'" and "Castle Rock 32'", most of them in the same two shades of green, and a legend from "up to 20 min" to "over 60 min"

The API part was right: one Route Matrix request with all towns as sources, Union Station as the only target, and sources_to_targets[i][0] read correctly. 155 lines, MapLibre 4.7.1.

Three things were weaker:

  • The towns were typed from memory: 20 names with approximate coordinates. That works for a demo, but your real list (customers, stores) has to come from somewhere, and a guessed coordinate gives a different drive time.
  • The color bands were too coarse: everything up to 20 minutes is the same dark green, so Lakewood (11 min) and Golden (19 min) look alike, and the "over 60 min" color is never used.
  • No-route answers disappear: a town whose cell is null is skipped without a word.

Prompt 2, precise: we named the library and version, the Places API request for the towns, the matrix request and how to read its answer, null handling, the color stops, the panel, the route on click and the click-to-move destination.

Page written by an AI assistant from the precise prompt: a MapLibre map with 31 cities and towns as dots labeled with their drive time to Union Station, from 6 minutes downtown to 37 in the foothills, and a panel with a gradient legend and the stats 31 origins, 6 min fastest, 21 min median, 37 min slowest, 9 of 31 within 15 min

The same result as our demo: 31 places, fastest 6, median 21, slowest 37 minutes, in 339 lines. The code also has the route on click, grey loading dots and a check for outdated answers (we tested the first load). One small difference: it counted "within 15 min" as 15 or less (9 towns), while the demo counts under 15 (7); two towns are exactly 15 minutes away.

What made the difference:

  • Say where the places come from. Without it, the assistant invents a list. Name the API call, or pass your own coordinates.
  • Give the color scale. A scale with steps every few minutes shows the pattern; broad bands hide it.
  • Mention null. Places with no route should show up as "no route", not vanish.
  • Define the thresholds. "Within 15 minutes" can mean < 15 or <= 15; say which.

Summary

  • Many places, one destination: one Route Matrix API request with all places as sources and the destination as the only target. Up to 1,000 pairs per request.
  • Read the answer from sources_to_targets[i][0]: time in seconds, distance in meters, null when there is no route.
  • Don't trust the circle: around Denver, places 22 km away are 19 or 30 minutes away by car.
  • Compare locations by running the same places against each candidate destination and counting who is within 15 or 20 minutes.
  • Show the route only for the place the user picks, with the Routing API.
  • Cost: max(sources, targets) × min(sources, targets, 10) credits for the matrix, 1 credit per 20 places from the Places API, 1 credit per route.

FAQ

How do I get drive times from many places to one destination?
Send one POST to https://api.geoapify.com/v1/routematrix with mode: "drive", all places as sources and the destination as targets: [{ location: [lon, lat] }]. The answer has one row per place with time (seconds) and distance (meters).

How many places can one request take?
Up to 1,000 source × target pairs. With one destination, that's up to 1,000 places. Split larger lists into several requests.

What does a matrix request cost?
max(sources, targets) × min(sources, targets, 10) credits. 31 places and one destination cost 31 credits; 347 places cost 347. The Free plan includes 3,000 credits a day.

Why is a cell null?
There is no route between that place and the destination, usually because the point is far from any mapped road. Show it as "no route" instead of a time.

Is the time from A to B the same as from B to A?
Not always. One-way streets, highway ramps and turn restrictions can make the two directions differ. Put the places in sources for "to the destination" and in targets for "from the destination".

Does the drive time include traffic?
By default no: traffic=free_flow assumes empty roads. traffic=approximated slows down roads that are typically busy. Neither is live traffic.

Should I use a matrix or isochrones?
A matrix gives exact times for a list of places you already have. An isochrone (Isoline API) draws the whole area reachable from one point, without a list. For "which of my customers are within 20 minutes?", use the matrix.


Try it

More drive-time tutorials:

Get a free API key at myprojects.geoapify.com and try it with your own places. Where would you put the office so most of your team is within 20 minutes? Tell us in the comments.

Top comments (0)