REST API
JavaScript
How to use the Naviaddress Platform API
in the javascript programming language?

TD;LR

To put it in a nutshell, to use the Naviadress APIyou need to make a simple GET or POST request with the supplied parameters. For example, you can get information about a given object with the help of such a short program:
let container = '7'; // This is an address container. 7 means Russia. 
let naviaddress = '0022'; // this is an address. [7]0022 – address of Naviaddress office in Russia
let url = 'https://staging-api.naviaddress.com/api/v1.5/Addresses/'
	+ container+'/' + naviaddress;

fetch(url).then((res1)=> 
	res1.json().then((res2)=>{
		console.log(res2.result);
	});
);
The example of program

Now let's write a small application that will determine the Naviaddress nearest to your location.

For this purpose, let's determine a sequence of actions:

  1. First of all, we get the current coordinates of the notebook or phone which the program will be executed on using the Geolocation API, embedded in any modern browser. The system should ask the user for access permission to this useful information.
  2. Around the received coordinates create a small square of four points spaced away from the initial point at a distance of one thousandth of a degree (we will write this value in advance to the DELTA constant).
  3. Get the list of all Naviaddresses inside this square. Limit the number of provided Naviaddresses using the LIMIT constant.
  4. Using the calculation of the Euclidean distance for each point we find the nearest Naviaddress to our location.
  5. And, finally, get data of the nearest Naviaddress.
Since the calls to the REST API is asynchronous, we use the new JavaScript async/await operator and wrap them into the asynchronous main() function. Actually, nothing prevents us from doing the same with traditional callback-calls.

main();

async function main() {
	let coords = await getLocation();
	let rect = createRect(coords,DELTA);
	let list = await getList(rect);
	let nearestAddr = findNearestAddress(coords, list);
	let address = await getAddress(nearestAddr);
	showResults(coords, list, address);
}
Define constants:
  • DELTA - sets up size of the square around the specified point.
  • LIMIT - limits the number of addresses given using the Map functions
const DELTA = 0.001; // Boundary for objects selection (in degrees)
const LIMIT = 100;   // Restriction of number of the returned objects


getLocation()

We will get the current location using the browser built-in function from the Geolocation API navigator.geolocation.getCurrentPosition (), which takes a callback function as a parameter - handler of the received coordinates.
function getLocation() {
	return new Promise((resolve,reject) => {
	    if (navigator.geolocation) {
	        navigator.geolocation.getCurrentPosition(
	        	(position)=>resolve(position.coords));
	    } else {
	    	alert(""Geolocation is not supported by your browser");
	    	reject();
	    }
	});
}
createRect()

Since we are going to search for naviaddresses around our location, let's create a square located at a delta distance horizontally and vertically from our coordinates.
function createRect(coords,delta) {
	return {
		lt_lat:coords.latitude - delta,
		lt_lng:coords.longitude - delta,
		rb_lat:coords.latitude + delta,
		rb_lng:coords.longitude + delta
	}
}
getList()

Now we need to get a list of objects located within a given square. This can be done using the Map method, in the parameters of which we must specify the coordinates of two corner points (upper left and lower right), as well as the output restriction at a time. I would like to add that this function supports pagination (which, however, is not used in this example).
function getList(rect) {
	return new Promise((resolve, reject) => {
		let url = new URL('https://staging-api.naviaddress.com/api/v1.5/Map');
		let params = {
			address_type: 'free',
			limit: LIMIT,
			lt_lat:rect.lt_lat, 
			lt_lng:rect.lt_lng,
			rb_lat:rect.rb_lat, 
			rb_lng:rect.rb_lng
		};
		url.search = new URLSearchParams(params);

		fetch(url).then((res1)=>
			res1.json().then((res2)=>resolve(res2.result))
		);
	});
}
findNearestAddress()

We should sort the resulting array using the simplest Euclidean distance formula. The closest object in the array is the desired address.
function findNearestAddress(coords, list) {
	list.sort((a,b)=>distance(a)-distance(b));
	return list[0];

	function distance(el){
		return Math.sqrt(Math.pow(el.point.lat - coords.latitude,2) 
				+ Math.pow(el.point.lng - coords.longitude,2));
	}
}
getAddress()

Now we need only receive data from the Naviaddress card which is available upon a simple GET request with indication of the container (country code) and the URL.
function getAddress(obj) {
	return new Promise((resolve, reject) => {
		let url = 'https://staging-api.naviaddress.com/api/v1.5/Addresses/'
			+ obj.container+'/'+obj.naviaddress;

		fetch(url).then((res1)=>
			res1.json().then((res2)=>resolve(res2.result))
		);
	});
}
Instead of the conclusion - How to get authorization?
getToken()


Although you need no authorization for the above task of getting Naviaddresses from the server, but for a number of tasks it is mandatory. Let's see how it is implemented in JavaScript. The following getToken() function returns an access token (more precisely, a promise, which in turn returns a token), which then can be used in other requests to the server via Naviaddress API.

It is necessary to have a key for access to the private API functions, which can be got by filling in the special registration form.
function getToken() {
	return new Promise((resolve,reject) => {
		let url = 'https://staging-api.naviaddress.com/api/v1.5/Sessions';
		let params = {
			password:'123456',    // Password and login to API access 
			Email:'abc@def.com'  //  Receive upon filling in a registration form 
		};

		fetch(url,
		{
		    headers: {
		      'Accept': 'application/json',
		      'Content-Type': 'application/json'
		    },
		    method: "POST",
		    body: JSON.stringify(params)
		})
		.then((res1) => 
			res1.json().then((res2) => {
				resolve(res2.token);
			});
		);
	});
}
You can get a token using this function as shown in the example below:
getToken().then((token) => {
     // Here you can call the special functions of Naviaddress API.
     console.log(token)
});
You can see the full code of the above program on a special page in GIST here.
written by: A.Gershun (09/10/2018)
Made on
Tilda