Created
February 20, 2020 09:34
-
-
Save nixjs/bee7eca15217711973e7c0287eeff6d8 to your computer and use it in GitHub Desktop.
haversine, get closest station
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
export const getClosestStation = (lat, lng, data) => { | |
const results = []; | |
data.forEach(element => { | |
const _dummy = haversine(lat, lng, element.latitude, element.longitude); | |
results.push({ ...element, distance: _dummy }); | |
}); | |
const min = Math.min.apply( | |
null, | |
results.map(item => item.distance), | |
); | |
return results.filter(elem => elem.distance === min)[0]; | |
}; |
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
export const getCoordinatesInRangePickupDropoff = (pickup, dropoff, routePolylineSelected) => { | |
if (_.isEmpty(routePolylineSelected)) { | |
return null; | |
} | |
const routePolylineDecoded = window.google.maps.geometry.encoding.decodePath(routePolylineSelected); | |
if (_.isEmpty(routePolylineDecoded)) { | |
return []; | |
} | |
const startIndex = routePolylineDecoded.findIndex(item => { | |
return haversine(item.lat(), item.lng(), pickup.latitude, pickup.longitude) === 0; | |
}); | |
const endIndex = routePolylineDecoded.findIndex(item => haversine(item.lat(), item.lng(), dropoff.latitude, dropoff.longitude) === 0); | |
return routePolylineDecoded.filter((_item, index) => index > startIndex && index < endIndex); | |
}; |
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
export const haversine = (lat1, lng1, lat2, lng2) => { | |
const [pi, asin, sin, cos, sqrt, pow, round] = ['PI', 'asin', 'sin', 'cos', 'sqrt', 'pow', 'round'].map(k => Math[k]); | |
const [rlat1, rlat2, rlng1, rlng2] = [lat1, lat2, lng1, lng2].map(x => (x / 180) * pi); | |
const dLat = rlat2 - rlat1; | |
const dLon = rlng2 - rlng1; | |
const radius = 6372.8; // km | |
return round(radius * 2 * asin(sqrt(pow(sin(dLat / 2), 2) + pow(sin(dLon / 2), 2) * cos(rlat1) * cos(rlat2))) * 100) / 100; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment