How to Migrate to NB Direction and Distance Matrix API from Google Maps Platform [HTML and JavaScript]

6 mins Read

January 22, 2023


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. 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


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

The 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, 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 and Google’s Distance Matrix APIs.

NextBillion vs Google’s Distance Matrix API

Features Google
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’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 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">
        <meta charset="UTF-8" />
        <title> Map</title>
		<link href="" rel="stylesheet" />
		* {
		   margin: 20;
		#map {
		   width: 100vw;
		   height: 100vh;
        <div id="map"></div>
            <script src=""></script>
		   (function () {
		        var map = new nextbillion.maps.Map(document.getElementById("map"), {
		        zoom: 8,
		        center: { lat: 40.730610, lng: -73.935242 }

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.


Migrating from Google to’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.,-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) {
	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) {
	directionShapes = null

Our response should look similar to the JSON schema below. More parameters can be added, as listed in the [Direction API Reference](

	"status": "Ok",
	"mode": "4w",
	"routes": [
		"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 = {
		center: place
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
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.


Migrating From Google to’s Distance Matrix API

The’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 ""*

		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',
	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:

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: '',
	headers: { }
	.then(function (response) {
	.catch(function (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 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?

Talk to Sales

Get routes that need no editing or on-road improvisations

Blog Img

Ready to up your game in scheduling, dispatch, and routing?

Request a Demo