Created
June 12, 2019 09:41
-
-
Save ravikp7/360a7fd838400d570ecadafe39820f8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const positions = { | |
Aman: { | |
latitude: 0, | |
longitude: 0, | |
}, | |
R1: { | |
latitude: 0, | |
longitude: 0, | |
}, | |
R2: { | |
latitude: 0, | |
longitude: 0, | |
}, | |
C1: { | |
latitude: 0, | |
longitude: 0, | |
}, | |
C2: { | |
latitude: 0, | |
longitude: 0, | |
}, | |
}; | |
const possibleRoutes = [ | |
['Aman', 'R1', 'C1', 'R2', 'C2'], | |
['Aman', 'R1', 'R2', 'C1', 'C2'], | |
['Aman', 'R1', 'R2', 'C2', 'C1'], | |
['Aman', 'R2', 'C2', 'R1', 'C1'], | |
['Aman', 'R2', 'R1', 'C2', 'C1'], | |
['Aman', 'R2', 'R1', 'C1', 'C2'], | |
]; | |
/** | |
* @description Convert angle from degree to radian | |
* @param {Number} deg - Angle in degree | |
* | |
* @returns {Number} Angle in Radian | |
*/ | |
const deg2rad = deg => deg * (Math.PI / 180); | |
/** | |
* @description Find distance between two geo locations using Haversine Formula | |
* @param {Number} lat1 - Latitude 1 | |
* @param {Number} lon1 - Longitude 1 | |
* @param {Number} lat2 - Latitude 2 | |
* @param {Number} lon2 - Longitude 2 | |
* | |
* @returns {Number} Distance | |
*/ | |
const findDistance = (lat1, lon1, lat2, lon2) => { | |
const R = 6371000; // Earth's radius in meteres | |
const dLat = deg2rad(lat2 - lat1); | |
const dLon = deg2rad(lon2 - lon1); | |
const a = | |
Math.sin(dLat / 2) * Math.sin(dLat / 2) + | |
Math.cos(deg2rad(lat1)) * | |
Math.cos(deg2rad(lat2)) * | |
Math.sin(dLon / 2) * | |
Math.sin(dLon / 2); | |
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); | |
return R * c; | |
}; | |
/** | |
* @description Find best route for the delivery | |
* | |
* @returns {Array} Route to follow | |
*/ | |
const getBestRoute = () => { | |
const distances = possibleRoutes.map(route => { | |
let totalDistance = 0; | |
for (let i = 0; i < route.length - 1; i++) { | |
const firstLocation = route[i]; | |
const secondLocation = route[i + 1]; | |
const distance = findDistance( | |
positions[firstLocation].latitude, | |
positions[firstLocation].longitude, | |
positions[secondLocation].latitude, | |
positions[secondLocation].longitude | |
); | |
totalDistance += distance; | |
} | |
return totalDistance; | |
}); | |
const minDistance = Math.min(...distances); | |
const bestRoute = possibleRoutes[distances.indexOf(minDistance)]; | |
return bestRoute; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment