Table of Contents
Introduction
Distance Matrix APIs
A Distance Matrix API is a service that computes and provides travel distance and travel time for a set of origins and destinations called a ‘matrix’. The matrix can consist of rows of the distances and time (duration) for each origin and destination pair.
Asides from returning a distance and duration for any pair of matrice, a distance matrix API also compare the different routes between an origin and a destination, and return the best route between them, providing optimization for speed and efficiency.
Map Directions APIs
A map Directions API is a web service that returns directions between an origin and a destination on a map in JSON or XML format. This is usually achieved using a client-side API that would compute the directions between two locations using an HTTP request to a map service.
The importance of these web services is represented in the key role they play in various commercial business operations and user experiences. It guarantees reliable business analytics to achieve customer satisfaction and targets.
NextBillion.ai offers an unrivaled way to enjoy these services by providing not just a much higher matrix size as compared to Google’s, but customization, flexible pricing, and easy integration. Migrating from Google’s Distance/Direction Matrix API to NextBillion’s is seamless and the benefits are worth the move.
What to Expect
At the end of this article, you should be able to:
- Understand how a distance and direction matrix work
- How to switch from Google’s API to NextBillion’s
- Advantages and benefits of NextBillion’s API
Pre-requisite
This article assumes you have knowledge of basic web technologies which includes HTML, CSS, and JavaScript. Knowledge of JavaScript’s async-await
functions would be a plus.
Why Migrate from Google to NextBillion.ai
The NextBillion.ai Distance and Direction API provide you with the flexibility and customizability you need, taking into consideration the fact that there are unique use cases depending on the modus-operandi of your business.
In addition to the above, the NextBillion API has a much higher matrix size, meaning it can calculate distances and estimated times of arrival between more than 5000 origins and destinations at a time; compare this to Google’s 25 at a time. This makes it the perfect fit for large-scale operations involving numerous points.
Furthermore, the NextBillion distance and direction API can be deployed on any cloud platform unlike Google’s which expectedly only works with the Google Cloud Platform.
Another great factor to consider is the pricing, as opposed to Google’s pay-as-you-go pricing which can get really costly as your business scale, NextBillion.ai offers custom and flexible pricing to suit your business model. These include pay-as-you-go, subscription, and customized pricing based on machine learning calculations.
Below is a tabular comparison between NextBillion.ai and Google’s Distance Matrix APIs.
NextBillion vs Google’s Distance Matrix API
Features | NextBillion.ai | |
---|---|---|
Max. Matrix Size: | 5000*5000 | 25 * 25 |
Customized Output: | Custom distance API outputs considering local restrictions, mixed fleets, etc. | Not supported |
Deployment: | Cloud-agnostic, supporting any cloud server | Based on the Google Cloud Console |
Pricing: | Flexible and customized pricing depending on the business model | Pay-as-you-go pricing model |
Getting Started With NextBillion API
For us to successfully get started with implementing NextBillion.ai’s direction and distance APIs, we have to request an API key, which is unique and would be required for making every request.
Now, you can get a unique API key using this link, which involves filling out a form with your name and work email required.
The very first step would be to render our NextBillion map on the user interface, so we can implement the main features. This is made possible by utilizing the NextBillion.ai SDK. Let’s illustrate this using JavaScript.
Firstly, we would render the map using a Content Delivery Network (CDN) by referencing it at the top of our index.html
page as shown below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>NextBillion.ai Map</title>
<link href="https://maps-gl.nextbillion.io/maps/api/css" rel="stylesheet" />
<style>
* {
margin: 20;
}
#map {
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="https://maps-gl.nextbillion.io/maps/api/js"></script>
<script>
(function () {
nextbillion.setApiKey('');
var map = new nextbillion.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: 40.730610, lng: -73.935242 }
});
})();
</script>
</body>
</html>
In the code above, we are using New York City’s coordinates as our initial render, feel free to modify properties like the zoom level, height, width and so on.
DIRECTION MATRIX
Migrating from Google to NextBillion.ai’s Direction API
Using NextBillion’s Directions API, let’s make a sample request to get the direction between New York City and New Jersey, the coordinates of both places is set as our origin and destination respectively. In addition, some optional parameters have been set to further suit our preference.
https://api.nextbillion.io/directions/json?origin=40.730610,-73.935242&destination=39.833851,-74.871826&session=R5mvdi&alternatives=false&altcount=1&annotations=false&approaches=unrestricted;unrestricted&avoid=toll&mode=4w&key=
Now we would use the async - await
logic in JavaScript to implement the direction shapes which render the directions API. You could utilize other JavaScript methods such as Promises
too.
This would be right inside our main function call which also contains the map SDK.
var directionShapes = null
document.getElementById('add-route').onclick = async function () {
if (directionShapes) {
return
}
var resp = await nextbillion.api.Directions({
origin: { lat: 24.9048329, lng: 74.5865747 },
destination: { lat: 26.82585465, lng: 75.80178009 },
})
directionShapes = map.renderDirections(resp)
}
document.getElementById('remove-route').onclick = function () {
if (!directionShapes) {
return
}
map.removeDirections(directionShapes)
directionShapes = null
}
Our response should look similar to the JSON schema below. More parameters can be added, as listed in the [Direction API Reference](https://docs.nextbillion.ai/docs/navigation/api/directions)
{
"status": "Ok",
"mode": "4w",
"routes": [
{
"geometry": "mognA{}oxMMjAMr@CLFBXFVJb@PZJ@@`Ad@`Ah@NHXNt@h@t@s@^]^]Tm@Xm@\\s@J]@K@S@K@O@KDYBKFWH]La@BOPg@DMJ]F]@Q@iAD}@?_@AMAWO}@Mq@Kg@Q{@EUG[G[Ia@Ou@?AKe@G]EUDMCKAK@ILFh@Xf@VlBz@dAf@D@d@Tp@Z^PhAj@ZPf@VHDDBTL`@Pb@T^NTLNHd@Tx@`@h@VPHnAt@LHl@X@@dAh@d@TVLFCFCfChAdAeBr@iA~ByDPWZg@PYRYJKJMFIFI?CAG@GDOBEDEHEL?JBDBFH@M?]HUPUp@gATg@JYHa@??Dk@DaA?ADwAD{BAOCIEEQJa@La@Ba@A_@KSMGEWYM_@Ga@?a@FW@IP]HKPOZQBMDIDIHIr@qAb@_AXu@L[DOBQ@I@MBABCh@UjAMtB[r@MtCYNCPENEVGVGDEBG?GDSFURs@HWp@wBBIPi@Ro@Tq@J[Pq@DO@C?M@_@?K?q@Ag@?IAi@?KDK?O?G?KBY?G^cCDWDUBO?AJe@Ha@FWDSH[DSHe@Py@\\eB~ATH@d@Hb@FH@H@ZF\\D`ANTD\\Fb@FH@JANGNKCKOWe@{@Ye@CGEIKQMU]k@OW?AQWOQIK}@iASYfCw@f@OXKpDeAr@Ud@M`@Mp@SPGf@Of@Of@OJCPGPGBN@TxBDjAB?a@A{AAcA?A@c@@u@@W?Y@I@IDMFMBEDIBGBKF[@KJcAHq@BS@IO?EQAG?EQ{AKcAQ_Bu@yHAA?EEOEOXSTQNINKdAo@VQLKb@[HGl@c@dAu@LOtAiAh@_@VQxAgAVMFGNELBFCFAF?F?V@Z@^BxDRF?F@b@@bCPnAHB?nAH@OD_AFw@F}@Dy@Dw@JoBBYC?CACCAE?C@A@EBABAB?@I?CFaADk@Do@H@t@BP@d@@~@B@K?A?K@A@O@W@Q@O?ADe@N?n@Dv@DB?J?`@BL?d@BVBGhA?BtAB",
"distance": 80000,
"duration": 11280,
"legs": [
{
"distance": {
"value": 2510
},
"duration": {
"value": 533
},
"steps": []
},
{
"distance": {
"value": 5169
},
"duration": {
"value": 1098
},
"steps": []
}
]
}
]
}
Let’s compare it with Google’s Direction API
In the code block below, there’s an object called DirectionsRequest
which contains some predefined key-value parameters. Afterward, the DirectionsService.route()
is called to initiate a request to the Directions service, passing a DirectionsRequest
object containing the input terms and a callback method to execute upon receipt of the response.
function initMap() {
var directionsService = new google.maps.DirectionsService();
var directionsRenderer = new google.maps.DirectionsRenderer();
var place = new google.maps.LatLng(24.9048329, -75.80178009);
var mapOptions = {
zoom:7,
center: place
}
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsRenderer.setMap(map);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin: start,
destination: end,
travelMode: 'DRIVING'
};
directionsService.route(request, function(result, status) {
if (status == 'OK') {
}
});
} directionsRenderer.setDirections(result);
In conclusion from the comparison made, NextBillion’s Direction API is achieved with less boilerplate using the async-await
method which allows for fewer lines of code and easy maintainability.
More query parameters can be used to call more features on the NextBillion directions API. Kindly check out the API reference here.
DISTANCE MATRIX
Migrating From Google to NextBillion.ai’s Distance Matrix API
The NextBillion.ai’s distance matrix API can take several sets of origins
and destinations
(locations) and it returns the distance between each of them.
When a location is selected on the map as either an origin or a destination, the SDK computes an array of both their latitudes and longitudes, and then the distances between them are returned in a JSON format which can be rendered on the UI of any software project.
Let’s create an asynchronous function that awaits data right inside the main function containing the map SDK. The function takes in an array of origins and destination coordinates respectively.
Afterward, we would call the function and log our results on the console. You can render the results however you want in your project.
(function () {
nextbillion.setApiKey('')*// Optional: you can set the API host if it differs from "api.nextbillion.io"*
nextbillion.setApiHost('')
var map = new nextbillion.maps.Map(document.getElementById('map'), {
zoom: 12,
center: { lat: 28.6139, lng: 77.209 },
})
async function requestDistanceMatrix() {
var response = await nextbillion.api.DistanceMatrix({
origins: [
{ lat: 13.01751434, lng: 77.60704545 },
{ lat: 13.00580657, lng: 77.61116532 },
{ lat: 13.00396673, lng: 77.63142137 },
],
destinations: [
{ lat: 12.9720182, lng: 77.55005387 },
{ lat: 12.95963913, lng: 77.64738587 },
{ lat: 12.93789063, lng: 77.61339692 },
],
mode: 'bike',
})
requestDistanceMatrix()
console.log(response) // check out the response in the browser's console
}
})()
Let’s compare with Google’s Distance API
Google’s Distance Matrix API steps are more demanding. It requires one to build a request URL before making a GET request using any client library such as Axios.
The request URL must take the format below:
https://maps.googleapis.com/maps/api/distancematrix/outputFormat?parameters
Where the
*outputFormat*
is either JSON or XML and- the
parameters
are the destinations and origins of the requested places.
compared to NextBillion’s quick asynchronous request, which can take multiple parameters.
var axios = require('axios');
var config = {
method: 'get',
url: 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Washington%2C%20DC&destinations=New%20York%20City%2C%20NY&units=imperial&key=YOUR_API_KEY',
headers: { }
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Furthermore, in NextBillion’s Distance Matrix request, asides from the origin and destination, other parameters can be queried depending on your custom need. For example, you can set avoid
and approaches
parameters, both of which accept a string, to indicate where to avoid and what is approaching.
Check the JSON response below:
{
"approaches": "string",
"avoid": "string",
"context": "string",
"debug": true,
"departure_time": 0,
"destinations": "string",
"key": "string",
"mode": "string",
"origins": "string"
}
Check out more on the distance matrix API reference.
In conclusion, the NextBillion.ai SDK and API offer customized distance and direction solutions alongside better scalability, customization, use cases, ease of deployment, and so on. An experience that would not just drive sales upwards, but also ensure better user experience and accuracy of data. Schedule a demo for any use case you have by clicking here.
Ready to get started?
Request a DemoTable of Contents