Hello Guys
Please let me start by saying hello and be gentle with me i’m new to Javascript.
I got it in my head to see if i could calculate the distance between 2 postcodes.
The following piece of code is rough and ready version and i’m not sure at all if i have got this right. Does the code follow convention or is it a mess and completely wrong. The code works up to the point of inserting the start and end coordinates to calculate the distance and return it back.
The post codes are returned with correct coordinates, but i also don’t know how to update the global variables for the start and end points at the top of the file.
Anyhow thanks for any input i appreciate it. I have removed my api keys and postcodes for security.
let calculateDistance = function(firstPostcode, secondPostcode) {
const fetch = require("node-fetch");
let start = "";
let end = "";
// Start Post Code
fetch(`https://api.postcodes.io/postcodes/${firstPostcode}`)
.then((response) => {
return response.json()
})
.then((startPostcode) => {
// Work with JSON data here
let long = JSON.parse(startPostcode.result.longitude);
let lat = JSON.parse(startPostcode.result.latitude);
start = (long + ',' + lat);
console.log(start);
})
.catch((err) => {
// Do something for an error here
});
// End Post Code
fetch(`https://api.postcodes.io/postcodes/${secondPostcode}`)
.then((response) => {
return response.json()
})
.then((endPostcode) => {
// Work with JSON data here
let long = JSON.parse(endPostcode.result.longitude);
let lat = JSON.parse(endPostcode.result.latitude);
end = (long + ',' + lat);
console.log(end);
})
.catch((err) => {
// Do something for an error here
});
// Calculate the distance
fetch(`https://api.openrouteservice.org/v2/directions/driving-car?api_key=**********************************************&start=${start}&end=${end}`)
.then((response) => {
return response.json()
})
.then((getDistance) => {
// Work with JSON data here
let distance = JSON.parse(getDistance.features[0].properties.summary.distance);
let miles = (distance/1609.344 + ' miles');
console.log(miles);
})
.catch((err) => {
// Do something for an error here
});
}
calculateDistance('firstPostCode', 'secondPostCode');
Thanks
Simon