Skip to main content

What is a distance matrix API?

A distance matrix API is a tool that calculates travel times and distances between any given set of origin and destination points. As simple as it may seem, it’s an extraordinarily powerful tool that finds utility across a spectrum of industries and use cases.

Regardless of whether you’re looking to go from one origin to many destinations (like a DoorDash driver dropping off multiple orders from one restaurant), from many origins to a single destination (consider how Uber assigns the nearest driver to pick you up) or from many origins to many destinations (think multiple Amazon delivery drivers covering all deliveries in a region), the distance matrix API helps you find the most efficient route or routes to achieve your goal.

A single call of the API returns a distance and ETA for the optimal path between each and every origin and destination pair. This data, generated in the form of a matrix, can then be passed through various other algorithms as required to generate the output you need to enhance your business operations.

The above image is what the output of a distance matrix API call looks like when there are two origins and two destinations involved — a 2×2 matrix. Each cell is called an ‘element’. The number of elements in an API call is equal to the number of origins multiplied by the number of destinations.

Overview

As you might imagine, distance matrix APIs play a crucial role in the operations of any mobility-based business — food and grocery delivery, ride hailing and ride sharing, micromobility, e-commerce, logistics, fleet management… you get the idea. All of these industries and more rely on distance matrix APIs to optimize their operations for maximum efficiency, scale, predictability and, ultimately, profit.

It’s worth noting, though, that while all of these various functions rely on the same basic concept of a distance matrix API, they each have their own industry-specific nuances and intricacies that come into play during the dispatch and route planning phases. Let’s take a look at cargo transportation as an example. For a company in this space, there are myriad rules to keep in mind — height and weight clearances; vehicle-, cargo– and time-based route restrictions; compliance regulations like hours spent on the road and so much more. For a ride-hailing service, on the other hand, it’s a completely different set of unique considerations that define the operation— peak traffic hours, high-demand regions, optimized routing for 2- and 4-wheelers, fare estimation, etc.

Clearly, the distance matrix API is not a one-size-fits-all solution. If optimal efficiency is to be attained, each vertical requires a customized solution that’s capable of accounting for its operational specificities. Don’t be confused by a common need for the base technology — plug-and-play APIs simply won’t cut it in the pursuit of maximizing profit.

Directions API vs distance matrix API

Speaking of confusion, there’s often some lack of clarity around the differences between directions APIs and distance matrix APIs. Understandably so, since there’s a bit of an overlap. There are two key distinctions that set these APIs apart from each other.

Let’s break them down. As we already know, a distance matrix API computes distances and ETAs between any given set of origins and destinations. A directions API finds the best possible route, based on distance or ETA, between any two given points — and then draws that route. The biggest difference between the two is immediately obvious in these definitions: Unlike the directions API, the distance matrix API’s functionality is not limited to calculations involving just two points. This is what makes distance matrix APIs so crucial in complex enterprise operations.

The second difference lies in the types of information that the APIs provide as output. While they both offer the same core information — travel times and distances — the directions API goes further to furnish you with additional details like road names along the route. Most importantly, it actually draws a path from origin to destination that you can follow. The distance matrix API, by contrast, simply generates a matrix of distances and ETAs for each origin and destination pair.

With the two APIs specializing in related but distinct functions, they are often used together in a single ecosystem, complementing each other’s capabilities. Let’s go back to the earlier example of Uber assigning the right drivers to the right customers. Assuming there are 50 customers, each requesting a ride at the same time, the company’s distance matrix API will perform a quick calculation to help identify the 50 most suitable drivers to connect them with. As each driver-customer pairing is confirmed, the directions API kicks into action, plotting the optimal route from the driver’s current location to the customer’s pick-up address.

Benefits of using a distance matrix API

As previously mentioned, any mobility-driven operation has much to gain from the use of a distance matrix API, in terms of operational efficiency. While the theme of the benefits it delivers is largely constant across all of them, each industry capitalizes on it in their own ways, and it means different things for their stakeholders. Let’s explore what some of the major relevant industries get out of distance matrix APIs.

Ride hailing

For ride-hailing services, finding and assigning the optimal driver for each customer’s ride request is arguably the most impactful benefit of the distance matrix API. This alone eliminates a significant number of miles driven by drivers and minutes spent waiting by customers — especially so if the API, like NextBillion.ai’s, is capable of processing live traffic information to optimize routing accordingly.

The API also becomes relevant in the case of rides with multiple stops, ensuring that the driver takes the most efficient path between all the necessary stops. Another function of the distance matrix API is that it allows customers to see drivers’ locations and estimated times of arrival.

All of the points mentioned above lead to three outcomes. The first of them is faster, better, cheaper rides — this keeps the customers happy and coming back for more. The second outcome is fuel savings — this puts more money in drivers’ pockets and smiles on their faces. The final outcome is the ability to complete more rides per hour — this boosts the unit economics, and thereby, profit, of the company itself. The distance matrix API has something in store for all the stakeholders in a ride-hailing operation. Everybody wins!

To see how NextBillion.ai’s Distance Matrix API was able to help a ride-hailing company lower its operational costs by 60%, read our case study here.

Trucking

Since trucking operations typically involve very large distances and numerous stops along the way, there’s plenty of scope for optimization around sequencing and routes.

As touched upon previously, routing for trucks is subject to various regulations, from time- and vehicle-based road access limitations to height-, weight- and cargo-dependent restrictions. If the distance matrix API is customizable to accommodate trucking-specific factors like these — once again, as NextBillion.ai’s is — then effective route optimization becomes a much quicker and simpler proposition. This also greatly increases the accuracy of ETA calculations, leading to better predictability of operations, and as a consequence, efficiency gains.

Distance matrix APIs also play a role in the sequencing of multiple stops. The distances and ETAs for each stop can be used as inputs for optimization engines to ensure that drivers follow the most efficient possible path between them. Trucking routes, particularly in the case of long-haul trucking, involve numerous stops during the journey for various reasons — refueling, rest breaks, meals, loading and unloading, toll booths and so on — so the utility of the API here is clear to see.

The theme of the benefits here is the same: fewer miles driven, more time and fuel saved, faster task completion, improved unit economics, etc. It’s also worth noting that trucks are expensive pieces of company-owned equipment, and when dealing with such long distances, wear and tear becomes a real concern. Because of this, the miles saved in this industry carry more significance to the business owners.

See here how NextBillion.ai’s Distance Matrix API improved ETA calculation accuracy by 37% and reduced mapping infrastructure costs by 40% for a leading logistics company.

E-commerce

When it comes to e-commerce, the sheer scale of operation is what lends itself to optimization via distance matrix API. With the last mile being the most cost-intensive step of the fulfillment process, it’s only logical that this is also where the most emphasis is placed on optimization.

As you might have guessed, with thousands of deliveries, if not more, to be made each day by a team of drivers, batching and sequencing of orders is one of the focus areas where companies stand to gain the most ground in terms of efficiency. Routing for all of these deliveries is, of course, another obvious focus area for optimization of the last mile.

We’ve already established that these are two functions in which the distance matrix API has a key role to play. Unsurprisingly, the operational benefits are very similar to those covered above — fuel and time savings, more customers served, better margins, etc. The differentiator here is scale; there’s scope for more of everything because of the volume of daily operations.

On-demand delivery

Retail on-demand deliveries like food and groceries have a lot in common with e-commerce in this context. The same challenges of order batching, sequencing and routing apply here. However, there is the additional concern of food freshness, which makes timely delivery incredibly important; this is a pressure that’s not felt quite as keenly in e-commerce. It’s because of this emphasis on speed that 10- or 15-minute delivery promises are becoming increasingly common. Such commitments further elevate the importance of sequencing and routing — and therefore, the function of the distance matrix API. Stale food makes for unhappy customers who would think twice before utilizing that delivery service again.

There is another interesting application for the distance matrix API in this space that arises due to the brick-and-mortar presence of restaurants and grocery stores. The API can be used to determine the ideal spots to add new outlet locations for further optimization of deliveries.

Here’s a detailed breakdown of how NextBillion.ai helped a top US-based food delivery company offer a superior customer experience while also saving 40% mapping costs.

Features of NextBiIlion.ai’s Distance Matrix API

NextBillion.ai’s proprietary Distance Matrix API is among the most customizable and performant APIs available in the market. How so, you ask? Let’s get into some of the main features that set it apart from the rest.

Large matrix size

The matrix size, or number of elements the API can support in a single call, is arguably the biggest defining feature of any distance matrix API, as this dictates how many origins and destinations it can handle with each call.

Most existing APIs support the market standard 25×25 matrix. This means they can resolve up to 25 origins and 25 destinations in a single call, giving you the distances and ETAs between every possible combination. NextBillion.ai’s Distance Matrix API, though, is capable of supporting a much larger matrix of 5000×5000 elements.

Such huge matrices are critical to maximizing the efficiency of large-scale operations like trucking and e-commerce that involve lots of vehicles and destinations. The flexibility of a large matrix enables you to optimize for however many stops you need, and even re-ordering of drop-off points if required. Improved batching, dispatching and routing all naturally follow as a consequence.

Custom + real-time data ingestion

Customizability is one of the tenets upon which NextBillion.ai’s Distance Matrix API was built. This is why it was engineered to ingest and process real-time traffic data as well as first- and third-party business-specific data with the help of advanced AI and ML algorithms.

No matter what line of business you’re in — logistics, ride hailing, last mile delivery, etc. — NextBillion.ai’s API can use relevant data from other similar companies to optimize its distance and ETA predictions for your operations. It has the ability to incorporate all those use-case-specific nuances we covered previously.

More importantly, it’s capable of analyzing your own historical ops data — driver behaviors, speed profiles, preferred routes, travel times, frequented POIs, etc. — and modifying its output accordingly. This means that the API can be heavily customized to your business and its unique intricacies. The more relevant data you feed the API, the better suited for your operations its output will be.

Such deep customization, combined with the capacity to process live traffic information, gives rise to incredibly accurate and reliable travel time and distance predictions, and all the benefits that entails.

Vehicle-specific profiles

Another example of NextBillion.ai’s commitment to performance and customizability lies in the ability of its Distance Matrix API to optimize for vehicle types. Most maps generally only support features for cars and sometimes two-wheelers. Enterprise fleets, though, are far more varied, often depending on everything from e-scooters and motorbikes to cars, vans, trucks and more.

This is an important factor to consider because these vehicles don’t all navigate the roads in the same manner; each type of vehicle will have its own routing characteristics and restrictions that must be accounted for. Apart from the weight, height and cargo restrictions we discussed earlier, it’s also worth keeping in mind that cars can’t access some of the routes that two-wheelers can, and larger vehicles can’t access some routes that cars can easily traverse.

NextBillion.ai’s Distance Matrix API incorporates all of these considerations into its calculations, delivering precise predictions consistently. It has profiles for all custom vehicle types and can even be used to optimize mixed-fleet operations. Without vehicle-specific profiles, a distance matrix APIs outputs are practically meaningless, unless your entire fleet is made up of regular cars.

Cloud-agnostic, on-premise deployment modes

When it comes to deployment modes, you’re looking for three things: flexibility, independence and performance. NextBillion.ai’s Distance Matrix API offers all three in abundance.

With the cloud-agnostic deployment feature, you can run the NextBillion.ai API on any cloud service of your choosing; you are not restricted to the services of any particular provider. Such flexibility allows you to seamlessly integrate the API into your existing infrastructure — no disruptions, no unnecessary expenses.

As great as cloud-agnostic deployment is, on-premise deployment offers even more value! Our API can be hosted on your internal infrastructure, delivering performance gains of up to 20x higher throughput and 3x lower latency. Better yet, this gives you complete control over the API deployment; no more dependence on cloud providers to maintain their servers or make any changes you need.

This level of performance and flexibility empowers you to scale at your own convenience without ever having to worry about whether your distance matrix API can keep up with the operational demands. Another factor in this regard is that on-premise deployments of the NextBillion.ai Distance Matrix API entitle you to an unlimited number of API calls at a fixed price, helping keep costs in check even at scale.

How to select a distance matrix API for your business

Selecting a distance matrix API solution for your business can be a daunting task; after all, a significant portion of your operations will be dependent on its outputs. Don’t worry, though. We’ll go through some comparisons of Google’s, Mapbox’s and NextBillion.ai’s offerings to help you make a well-informed decision.

Here are some factors you’ll need to consider when choosing a distance matrix API for your business, and how each of the APIs compare:

Scale

How many vehicles do you have in your fleet? How many deliveries/rides/stops do you typically need to optimize for? Do you envision your business scaling into something bigger down the line? All of these questions will affect your choice of API. After all, if you’re running a large operation that involves numerous vehicles, pick ups and drop offs, then you’ll need an API that can keep up accordingly.

We know that the size of the matrix matters when it comes to bigger operations, and that one of the NextBillion.ai API’s differentiating features is its large matrix of 5000×5000 elements. How do the Google and Mapbox offerings compare? Well, they both support no more than the market standard 25×25 matrix.

So then, the answer is quite clear cut as far as scale is concerned. If you’re running a relatively small operation, either the Google or Mapbox API should suffice. However, if you’re running a larger operation, you would be best served by the NextBillion.ai Distance Matrix API’s bigger matrix size.

Even if your operation is currently a small one but you want to one day expand it to something bigger, NextBillion.ai would be the choice for you. Why? Our API offers the most bang for your buck for every tier of usage-based pricing (more on this later in this section)! So, while cost can quickly become a bottleneck when scaling up with other APIs, it’ll never be a cause for worry with NextBillion.ai.

Performance

Intensive tasks like route optimization and live data integration often require a huge number of API calls in very short periods of time. If your business functions involve a lot of such tasks, you’re going to need a high-performance solution for seamless operations.

This is one of the areas where the deployment modes we went over earlier come into play. We already saw that NextBillion.ai’s Distance Matrix API, with its on-premise deployment option, offers 20x higher throughput and 3x lower latency when compared to typical cloud deployments.

Mapbox’s Matrix API and Google’s Distance Matrix API, though, do not support on-premise deployments; these solutions must be deployed in the cloud. This limitation means that regardless of the quality of the APIs themselves, they will be muzzled by the inherent performance drawbacks of the cloud, which local servers can circumvent.

So, the question then becomes, how important is API performance to the smooth running of your business operations? If high performance is mandatory, then on-premise deployment — and by extension, NextBillion.ai’s Distance Matrix API — is the only way to go.

Independence

Independence is another consideration where deployment modes are relevant. First, let’s address independence from being locked in with a specific cloud provider. Some APIs are required to be deployed in a specific cloud provider’s environment. This can be undesirable for many reasons, the most common of which is that it’s quite costly to uproot your existing infrastructure and replace it — possibly even with an inferior solution — for the sake of API compatibility. Thankfully, all three of the distance matrix APIs in discussion here support cloud-agnostic deployments, so you’ll never be beholden to the services of a particular cloud provider with them.

Since all three APIs are on even footing in that regard, let’s discuss another level of independence: independence from cloud providers altogether. Liaising with your cloud provider’s support team every time you need to make an adjustment can quickly become a cumbersome process, especially if it’s a frequent occurrence in your operations. In the case of critical and time-sensitive issues, this quickly goes from being a mere inconvenience to a costly liability. Server maintenance and downtime is another possible point of failure that lies in the hands of a third party in typical cloud deployments. If you want complete control over your operation, this is not acceptable. That’s why we have on-premise deployments — to eliminate any sort of dependence on external cloud providers.

Here, the APIs in focus are no longer on even footing, as Mapbox and Google do not allow for on-premise deployments — only NextBillion.ai does. Thus, if you’re looking for total control of your API deployment, there’s only one solution that will give you what you need.

Customizability

Customizability is a big one if you’re in pursuit of the most reliably precise travel times and distances from your distance matrix API. For optimal results, the API needs to be able to ingest and intelligently learn from relevant proprietary as well as external data to modify its output accordingly.

We’ve already seen how NextBillion.ai’s Distance Matrix API has this capability for vehicle- and use-case-specific customizations. Practically any data that’s germaine to the context of your business can be harnessed to enhance the output of the API. Vehicle type, cargo type, time of day during travel, hyper-local nuances like regional road rules and disruptions, and so much more can all be put to good use in refining your vehicle-based operations.

In contrast to this, neither the Google Distance Matrix API nor the Mapbox Matrix API afford you anywhere near such granular customization. As a result of this lack of customizability to any given use case, these APIs are simply unable to match the extreme accuracy that their NextBillion.ai counterpart brings to the table. In this facet of the comparison, your choice of API becomes a function of the level of precision you require for your business operations.

Affordability

It will come as no surprise to anybody at all that cost is one of the first and biggest considerations behind any business decision — no explanations required there.

Every organization makes and spends money differently, and this has huge implications on how purchase and renewal decisions are made. This is why NextBillion.ai’s Distance Matrix API gives you flexible pricing options — you can find something that works for you, no matter what kind of business model you operate on. Pricing models are as follows:

Pay-as-you-go — Pricing based on volume of API calls

Subscription — Fixed fee with unlimited API calls for on-premise deployment

Customized — Pricing based on ML model deployed

Yes, you read that right — with an on-premise deployment of our API, you get unlimited calls at a fixed cost! It’s not hard to see the value you could draw from this.

So, how do Google’s and Mapbox’s distance matrix APIs stack up as far as pricing is concerned? Not well; their pricing models are rigid and inflexible. As we touched upon previously, NextBillion.ai offers the most value for money at every level of usage. Below is a direct comparison of the usage-based pricing for each of the APIs.

Number of elements per Month NextBillion.ai Mapbox Google Maps
1 to 100K Free Free $5.0
100K to 500K $1.5 $2.0 $4.0
500K to 1M $1.2 $1.6 $3.0
1M to 5M $0.9 $1.2 $1.5
5M to 10M $0.75

As you can see, it’s clear that NextBillion.ai offers more for less. But that’s not all — NextBillion.ai gives you the opportunity to save even more with its BYOD (bring your own data) plan. If you furnish your own historical ops data to feed into the API, we’ll give you a 20% discount. This means that with us, you get the best-performing API at a significantly lower cost than its competitors!

There’s only one winner in this comparison, and it’s NextBillion.ai, without a shadow of a doubt.

Developers — Getting started with NextBillion.ai’s Distance Matrix API

Request parameters
NAME REQUIRED/ OPTIONAL TYPE FORMAT AND USAGE DESCRIPTION
destination Required Object Format: lat,lng | lat,lng…
“41.349302,2.136480|
41.389925,2.136258|
41.357961,2.097878”
Destinations are the ending coordinates of your route. Ensure that destinations are at valid land locations. Multiple destinations are separated by a pipe symbol.
origin Required Object Format: lat,lng
“41.349302,2.136480|
41.389925,2.136258|
41.357961,2.097878”
Origins are the starting points of your route. Ensure that origins are valid land locations to calculate a route. Multiple origins are separated by a pipe symbol.
mode Optional String Values: car|auto|bike|escooter|4w| 2w|0w…. Default: “4w” A string parameter to set which driving mode the route should use. For example, if you use 4w, the API will return a route for 4-wheelers. 0w will return a route for pedestrians.
departureTime Optional Number Format: unix timestamp Unit: seconds Default: 0 Sets the time of departure. The response will return a route based on traffic for that specific departure time.
session Optional String Unique session ID for trip identification Default: “” Unique session ID. If set, the response will reuse cached trip characteristics. Note: Helps to reuse cached trip characteristics when set.
debug Optional Boolean Default: false Set to ‘True’ to show debugging information.
key Optional String 32 bit alphanumeric string API key for authentication.
avoid Optional String Can accept values of “toll”, “highway”, ”highways”, Set this value to avoid either tolls, highways or ferry routes.

Migrating to NextBillion.ai’s Distance Matrix API

Having seen all that the NextBillion.ai Distance Matrix API has to offer, you might be wondering how difficult it’d be to migrate if you’re already using Google’s or Mapbox’s distance matrix services. Good news — it’s not difficult at all! All it takes is just a few small modifications.

From Google Distance Matrix API

With the Google Distance Matrix service, some of your API calls probably look similar to the code presented below. Here we use the Axios library to fetch from the Google Maps API endpoint with a set of origins and destinations, and output results to the terminal to show travel times between each start and end point.

var axios = require(‘axios’); 
const colorize = require(‘./utils’); 
module.exports = async function dm(originArray, destArray, points_origins, points_destinations, precision) 
{ 
  let idx = 0; 
  let origin_index = ‘’;
  let dest_index = ‘’;
  orig_pts = ‘’, dest_pts = ‘’; 
  points_origins.forEach(pt => { 
    orig_pts += pt.geometry.coordinates[0].toFixed(precision) + ‘,’ + pt.geometry.coordinates[1].toFixed(precision) + ‘;’; 
    origin_index += idx++ + ‘;’; 
}); 

points_destinations.forEach(pt => { 
  dest_pts += pt.geometry.coordinates[0].toFixed(precision) + ‘,’ + pt.geometry.coordinates[1].toFixed(precision) + ‘;’; 
  dest_index += idx++ + ‘;’; 
}); 

dest_pts = dest_pts.slice(0, dest_pts.length - 1); 
origin_index = origin_index.slice(0, origin_index.length - 1); 
dest_index = dest_index.slice(0, dest_index.length - 1); 

let mbUrl = `https://api.mapbox.com/directions-matrix/v1/mapbox/driving-traffic/${orig_pts}${dest_pts}?sources=${origin_index}&destinations=${dest_index}&access_token=${process.env['MAPBOX_TOKEN']}`; 

var config = { 
  method: ‘get’, 
  url: mbUrl, 
  headers: {} 
} 

await axios(config) 
.then( res => { 
   process.stdout.write(colorize(44,’…Mapbox result… ‘));     
   process.stdout.write(‘\n’);

Output from the Mapbox API call will look similar to this. 
…Mapbox result… 
                 | 37.7027,-122.4330| 37.7373,-122.4477| 37.7698,-122.4552| 
37.6195,-122.4756|              1198|              1180|              1695| 
37.6334,-122.4450|              1122|              1104|              1555| 
37.5791,-122.3562|              1547|              1373|              1829|

The highlighted portion of the code block above is where you’ll need to make changes in order to start using NextBillion.ai’s distance matrix service for the same set of points.

There are very few changes needed; the highlighted section in the below image shows what the modified code and its output should look like.

For NextBillion.ai, we make use of a HTTP POST with the body containing the origins, destinations, travel profile (car, truck etc.) and optional departure timestamp. This enables us to present large matrix problems, in the order of thousands of elements, to the endpoint without exceeding URI length limits.

let axios = require(‘axios’); 
const colorize = require(‘./utils’); 

module.exports = async function dm(originArray, destArray, orig_pts, dest_pts, precision) { 

// NBAI JSON will use POST endpoint (concise) 
   const apiKey = process.env[‘API_KEY’]; 
   const apiHost = process.env[‘API_HOST’]; 
// With NBAI, you can set departure time and it will 
// use historic traffic patterns for this date/time 
// Change mode to other transport modes as needed 
let bodyRequest = { 
   “departure_time”: Math.round(new Date().getTime() / 1000), 
   “origins”: orig_pts, 
   “destinations”: dest_pts, 
   “mode”: “car” 
}; 
let config = { 
   method: ‘post’, 
   url: `${apiHost}/distancematrix/json-concise?key=${apiKey}`, 
   data: bodyRequest 
} 

await axios(config) 
  .then((res) => { 
     process.stdout.write(colorize(45,’…NB.ai result… ‘)); 
     process.stdout.write(‘\n’); 
     process.stdout.write(colorize(91, ‘ ‘.toString().padStart(19, ‘ ‘))); 
     destArray.forEach( pt => { 
        process.stdout.write(‘|’ + colorize(91, pt.padStart(19, ‘ ‘))); 
     }); 
     process.stdout.write(‘|’ + ‘\n’); 
     var idx = 0; 
     var dm = res.data; 
     dm.rows.forEach( row => { 
       process.stdout.write(colorize(93, originArray[idx++].padStart(19, ‘ ‘) + ‘|’)); 
      row.forEach( element => { 
         process.stdout.write(colorize(92, element[0].toString().padStart(precision + 15, ‘ ‘))); 
         process.stdout.write(‘|’); 
      }); 
      process.stdout.write(‘\n’); 
    }); 
 }).catch((err) => { 
      console.log(err); 
  }) 
}

Output from the NB.ai API call will look similar to this. 
…NB.ai result… 
                 | 37.6735,-122.4531| 37.6157,-122.4595| 37.6825,-122.4387| 
37.7109,-122.4893|               551|              1125|               775| 
37.6431,-122.4792|               538|               699|               745| 
37.7401,-122.4408|               703|              1277|               927|
From Mapbox Matrix API

Migrating from the Mapbox API is a similarly painless process — we just need a bit more modification of inputs and outputs to deal with the returned elements from Mapbox and lat/lon input ordering. See the module `mb_dm.js` in the code repository for the reference implementation from Mapbox that we modified and transitioned to NextBillion.ai.

var axios = require(‘axios’); 
const colorize = require(‘./utils’); 
module.exports = async function dm(originArray, destArray, points_origins, points_destinations, precision) 
{ 
  let idx = 0; 
  let origin_index = ‘’;
  let dest_index = ‘’;
  orig_pts = ‘’, dest_pts = ‘’; 
  points_origins.forEach(pt => { 
    orig_pts += pt.geometry.coordinates[0].toFixed(precision) + ‘,’ + pt.geometry.coordinates[1].toFixed(precision) + ‘;’; 
    origin_index += idx++ + ‘;’; 
}); 

points_destinations.forEach(pt => { 
  dest_pts += pt.geometry.coordinates[0].toFixed(precision) + ‘,’ + pt.geometry.coordinates[1].toFixed(precision) + ‘;’; 
  dest_index += idx++ + ‘;’; 
}); 

dest_pts = dest_pts.slice(0, dest_pts.length - 1); 
origin_index = origin_index.slice(0, origin_index.length - 1); 
dest_index = dest_index.slice(0, dest_index.length - 1); 

let mbUrl = `https://api.mapbox.com/directions-matrix/v1/mapbox/driving-traffic/${orig_pts}${dest_pts}?sources=${origin_index}&destinations=${dest_index}&access_token=${process.env['MAPBOX_TOKEN']}`; 

var config = { 
  method: ‘get’, 
  url: mbUrl, 
  headers: {} 
} 

await axios(config) 
.then( res => { 
   process.stdout.write(colorize(44,’…Mapbox result… ‘));     
   process.stdout.write(‘\n’);

Output from the Mapbox API call will look similar to this. 
…Mapbox result… 
                 | 37.7027,-122.4330| 37.7373,-122.4477| 37.7698,-122.4552| 
37.6195,-122.4756|              1198|              1180|              1695| 
37.6334,-122.4450|              1122|              1104|              1555| 
37.5791,-122.3562|              1547|              1373|              1829|

Once again, the migration just requires some changes to the API endpoint, HTTP method and the request body. The sample code shown in the Google example above applies to this migration as well.

Take a look at the sample project in our repo, where we have the three implementations side by side for comparison.

Conclusion

When all is said and done, regardless of which mobility-based industry you operate in, the scale — current or future — of your business, your unique use case requirements and your existing tech stack setup, NextBillion.ai’s Distance Matrix API offers better accuracy, performance and value than the other major players in the market.

To find out more about what exactly NextBillion.ai’s Distance Matrix API can do for your specific business, reach out to us here.

🎉 NextBillion.ai Raises Series B Funding

X