Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active May 25, 2022 11:34
Show Gist options
  • Save leommoore/f476d2a103ad450df09f to your computer and use it in GitHub Desktop.
Save leommoore/f476d2a103ad450df09f to your computer and use it in GitHub Desktop.
Haversine - Distance between two points

Haversine - Distance between two points

// haversine
// By Nick Justice (niix)
// https://github.com/niix/haversine

var haversine = (function() {

  // convert to radians
  var toRad = function(num) {
    return num * Math.PI / 180
  }

  return function haversine(start, end, options) {
    var miles = 3960
    var km    = 6371
    options   = options || {}

    var R = options.unit === 'km' ? km : miles

    var dLat = toRad(end.latitude - start.latitude)
    var dLon = toRad(end.longitude - start.longitude)
    var lat1 = toRad(start.latitude)
    var lat2 = toRad(end.latitude)

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2)
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))

    if (options.threshold) {
      return options.threshold > (R * c)
    } else {
      return R * c
    }
  }
})()

module.exports = haversine

Usage

haversine(start, end, options)
var haversine = require('haversine')

start = {
  latitude: 30.849635,
  longitude: -83.24559
}
end = {
  latitude: 27.950575,
  longitude: -82.457178
}

console.log(haversine(start, end))
console.log(haversine(start, end, {unit: 'km'}))
console.log(haversine(start, end, {threshold: 1}))
console.log(haversine(start, end, {threshold: 1, unit: 'km'}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment