Skip to content

Instantly share code, notes, and snippets.

@pzi
Last active August 29, 2015 14:17
Show Gist options
  • Save pzi/2aff7f5e8130991be3c6 to your computer and use it in GitHub Desktop.
Save pzi/2aff7f5e8130991be3c6 to your computer and use it in GitHub Desktop.
#= require jquery
#= require jquery-sort
$locationsContainer = $('#locations')
locationsData = $locationsContainer.data('locations')
currentCoords = latitude: 0, longitude: 0
locations = []
firstRun = true
if typeof (Number::toRad) is 'undefined'
Number::toRad = ->
this * Math.PI / 180
getDistance = (start, end, decimals) ->
decimals = decimals or 2
earthRadius = 6371 # km
lat1 = parseFloat(start.latitude)
lat2 = parseFloat(end.latitude)
lon1 = parseFloat(start.longitude)
lon2 = parseFloat(end.longitude)
dLat = (lat2 - lat1).toRad()
dLon = (lon2 - lon1).toRad()
lat1 = lat1.toRad()
lat2 = lat2.toRad()
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 = earthRadius * c
Math.round(d * Math.pow(10, decimals)) / Math.pow(10, decimals)
success = (position) ->
console.log 'got location', position
if currentCoords.latitude isnt position.coords.latitude and currentCoords.longitude isnt position.coords.longitude
currentCoords = position.coords
sortLocationsByDistance()
buildButtons()
sortButtons()
error = (error) ->
buildButtons()
options =
enableHighAccuracy: false
maximumAge: 30000
timeout: 25000
sortLocationsByDistance = ->
locations = for location in locationsData
location.distance = getDistance(location, currentCoords, 4)
location.distance_human = location.distance + 'km'
location
buildButtons = ->
if firstRun
html = for location in locations
buildButton(location)
$locationsContainer.html(html)
firstRun = false
else
for location in locations
if ($location = $("location-#{location.id}")).length
$location.data('distance', location.distance)
$location.find('.distance').text(location.distance_human)
buildButton = (location) ->
html = """
<button class="category-#{location.category}" id="location-#{location.id}" data-distance="#{location.distance}">
<span class="distance">#{location.distance_human}</span>
<span class="label">#{location.name}</span>
</button>
"""
sortButtons = ->
$locationsContainer.children().sortElements (a, b) ->
if $(a).data('distance') > $(b).data('distance') then 1 else -1
if navigator.geolocation
$locationsContainer.text 'Finding location...'
navigator.geolocation.watchPosition(success, error, options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment