(opens in a new tab)gmap cloud
Talk to usContact
RoutingIntermediate2 min readIncludes code

Pick the nearest warehouse with a time–distance matrix

Straight-line distance often picks the wrong warehouse because of rivers, bridges and one-way streets. A time–distance matrix uses the real road network for every warehouse–delivery pair in one call.

· GMap Cloud

Call the matrix API

sources are the warehouses, targets are the delivery points; costing sets the travel mode (auto is car).

cURL
curl 'https://cloud.gmap.vn/api/tsp/route/sources_to_targets' \
  --header 'x-api-key: public-gmap-cloud-x-api-key-demo' \
  --header 'content-type: application/json' \
  --data '{
    "sources": [{ "lat": 21.0285, "lon": 105.8542 }, { "lat": 21.0367, "lon": 105.8352 }],
    "targets": [{ "lat": 21.015, "lon": 105.847 }],
    "costing": "auto"
  }'
WarehouseTimeDistance
Hoàn Kiếm (21.0285, 105.8542)302 s (~5 min)2.733 km
Ba Đình (21.0367, 105.8352)319 s (~5.3 min)3.428 km

sources_to_targets[i][j] is the result from warehouse i to delivery point j; time is in seconds and distance in the returned units (kilometers).

Pick a warehouse in JavaScript

JavaScript
const warehouses = [
  { name: 'Hoàn Kiếm', lat: 21.0285, lon: 105.8542 },
  { name: 'Ba Đình', lat: 21.0367, lon: 105.8352 },
];
const order = { lat: 21.015, lon: 105.847 };

const response = await fetch(
  'https://cloud.gmap.vn/api/tsp/route/sources_to_targets?x-api-key=public-gmap-cloud-x-api-key-demo',
  {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({
      sources: warehouses.map(({ lat, lon }) => ({ lat, lon })),
      targets: [order],
      costing: 'auto',
    }),
  },
);
const { sources_to_targets: rows } = await response.json();
const nearest = rows
  .map(([cell], index) => ({ ...warehouses[index], minutes: cell.time / 60, km: cell.distance }))
  .sort((a, b) => a.minutes - b.minutes)[0];
// → Hoàn Kiếm, ~5 minutes, 2.733 km

Good to know

  • Times are estimates from the routing model and do not include live traffic.
  • Batch several orders in one request (several targets) to reduce calls.
  • For multi-stop trips, use the stop-ordering API after choosing the warehouse.