Hi everyone, so after properly intruducing myself, i would like to start my development sharing journey by sharing how i made a simple distance calculator from two points with javascript and also using this a source of creating a fare price generator for hybrid ride applications.
TOOLS USED:
- Text-editor: Atom
- Your computer!
Moving forward, for each step,I'll share a code snippet, so let's get started.
Step 1
We create a method in which we return a promise to resolve or reject on error, inside this method the arguments are:
- The user's latitude
- The user's longitude
- The destination latitude
- The destination logitude.
Here's how to do that:
calcCrow = (lat1, lon1, lat2, lon2) => {
return new Promise((resolve, reject) => {
//codes goes in here to while success are resolved and failures are rejected
})
}
Moving forward, we calculate our redius for each of the provided latitudes which looks like this:
let radlat1 = Math.PI * lat1 / 180;
let radlat2 = Math.PI * lat2 / 180;
then also, we calculate the theta and find the radius for that too using the longitude:
let theta = lon1 - lon2;
let radtheta = Math.PI * theta / 180;
Then to calculate our distance, we sum up the product of the sin of the radius and the product of the cosines of the radius calculated:
let dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
We check to see if our distance is greater than 1, cos we should have it lesser so that we can run our arccosing to return our real distance and we convert to any unit we want.
to check:
if (dist > 1) {
dist = 1;
}
Moving forward,
dist = Math.acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
we use this to get our value in meters, then convert to Km
dist = dist * 1.609344
PUTTING ALL TOGETHER
calcCrow = (lat1, lon1, lat2, lon2) => {
return new Promise((resolve, reject) => {
let radlat1 = Math.PI * lat1 / 180;
let radlat2 = Math.PI * lat2 / 180;
let theta = lon1 - lon2;
let radtheta = Math.PI * theta / 180;
let dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
if (dist > 1) {
dist = 1;
}
dist = Math.acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515; //meters
dist = dist * 1.609344
resolve(Math.round(dist));
})
}
This function would return the distance between the two provided points in Kilometers, now to use this to generate a fare rate for a particular base fare:
Let's assume our base is $1.50
We can the write a method that calculates our fare after the distance calculator function promise resolves:
calcRate = (lat1, lon1, lat2, lon2) => {
return new Promise((resolve, reject) => {
let fare = 1.50;
this.calcCrow(lat1, lon1, lat2, lon2).then(res => {
let total = (res * fare);
resolve(total);
})
});
}
So with that it's all set to use, i hope this helps, feel free to drop a comment and questions on this, cheers