Skip to content

Instantly share code, notes, and snippets.

@markopostma
Created October 23, 2015 13:10
Show Gist options
  • Select an option

  • Save markopostma/5caffae8d2ca0ff4f7f5 to your computer and use it in GitHub Desktop.

Select an option

Save markopostma/5caffae8d2ca0ff4f7f5 to your computer and use it in GitHub Desktop.
Get distance between 2 lat + lng coordinates with coffee
class @geoLocation
constructor: ->
getLocation()
getLocation = ->
if navigator.geolocation
navigator.geolocation.getCurrentPosition showLocation
else
console.warn 'Geolocation is not supported by this browser.'
return
showLocation = (position) ->
lat = position.coords.latitude
lng = position.coords.longitude
$('.locations-col .location').each (index, item) ->
if $(item).find('.distance').length
location_lat = $(item).data('lat')
location_lng = $(item).data('lng')
distance = calcCrow lat, lng, location_lat, location_lng
if distance
console.log Math.round distance
calcCrow = (lat1, lon1, lat2, lon2) ->
R = 6371
# km
dLat = toRad(lat2 - lat1)
dLon = toRad(lon2 - lon1)
lat1 = toRad(lat1)
lat2 = toRad(lat2)
a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2)
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
d = R * c
d
# Converts numeric degrees to radians
toRad = (Value) ->
Value * Math.PI / 180
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment