Skip to content

Instantly share code, notes, and snippets.

@chris-kobrzak
Forked from moshmage/withinRadius.js
Last active February 20, 2020 20:53
Show Gist options
  • Save chris-kobrzak/aa1bce2d7d586218b0a908f49a96a13d to your computer and use it in GitHub Desktop.
Save chris-kobrzak/aa1bce2d7d586218b0a908f49a96a13d to your computer and use it in GitHub Desktop.
Compares two points' latitude and longitude and returns true if within provided metres
const {asin, cos, sin, sqrt, PI} = Math
const EARTH_RADIUS_KM = 6371
const METERS_IN_KM = 1000
// const deg2rad = n => Math.tan(n * (Math.PI / 180))
const convertDegToRad = degries => degries * (PI / 180)
/**
* is One Point within Another
* @param point {Object} {latitude: Number, longitude: Number}
* @param interest {Object} {latitude: Number, longitude: Number}
* @param kms {Number}
* @returns {boolean}
*/
function isWithinRadius(
{ latitude, longitude },
{ referenceLatitude, referenceLongitude },
radiusMetres
) {
const virtualApexLatitude = convertDegToRad(referenceLatitude - latitude)
const virtualApexLongitude = convertDegToRad(referenceLongitude - longitude)
// TODO Work out a meaningul name for a and c...
const a =
sin(virtualApexLatitude / 2) * sin(virtualApexLatitude / 2) +
cos(convertDegToRad(latitude)) *
cos(convertDegToRad(referenceLatitude)) *
sin(virtualApexLongitude / 2) *
sin(virtualApexLongitude / 2)
const c = 2 * Math.asin(sqrt(a))
const distance = EARTH_RADIUS_KM * c
return distance <= radiusMetres * METERS_IN_KM
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment