Commits

Marco Yuen  committed 5f00262

Add formula to calculate distance. Add more JS error checking.

  • Participants
  • Parent commits 96d2856

Comments (0)

Files changed (3)

File research/haversine.py

+#!/usr/bin/python
+
+import math
+
+# http://www.platoscave.net/blog/2009/oct/5/calculate-distance-latitude-longitude-python/
+def haversine(origin, destination):
+    lat1, lon1 = origin
+    lat2, lon2 = destination
+    radius = 6371 # km
+
+    dlat = math.radians(lat2-lat1)
+    dlon = math.radians(lon2-lon1)
+    a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) \
+        * math.cos(math.radians(lat2)) * math.sin(dlon/2) * math.sin(dlon/2)
+    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
+    d = radius * c
+
+    return d
+
+home    = [40.7599573, -73.9921683]
+ny_penn = [40.750046, -73.992358]
+pton    = [40.343398, -74.659872]
+
+
+dist = haversine(home, ny_penn)
+print(dist)
+
+dist = haversine(home, pton)
+print(dist)
+

File resources/public/js/location.js

 $(function() {
   if (navigator.geolocation) {
-    navigator.geolocation.getCurrentPosition(success, error);
+    navigator.geolocation.getCurrentPosition(success, handleError,
+                                             {enableHighAccuracy: true});
   } else {
     alert('Geolocation not supported');
   }
     $("#lat").html(position.coords.latitude);
   }
 
-  function error() {
+  function handleError(error) {
     console.log("No location");
+    switch(error.code)
+    {
+      case error.PERMISSION_DENIED: alert("user did not share geolocation data");
+      break;
+
+      case error.POSITION_UNAVAILABLE: alert("could not detect current position");
+      break;
+
+      case error.TIMEOUT: alert("retrieving position timed out");
+      break;
+
+      default: alert("unknown error");
+      break;
+    }
   }
 });
 

File src/nextrain/utils.clj

+(ns nextrain.utils)
+
+(def origin  [40.7599573, -73.9921683])
+;(def ny_penn [40.750046, -73.992358])
+;(def pton    [40.343398, -74.659872])
+
+(def earth-radius 6371)
+(def cos    #(Math/cos %))
+(def sin    #(Math/sin %))
+(def radian #(Math/toRadians %))
+(def sqrt   #(Math/sqrt %))
+(def atan2  #(Math/atan2 % %2))
+(def pow    #(Math/pow % %2))
+
+(defn haversine-dist
+  [[src-lat src-lon] [dest-lat dest-lon]]
+  (let [dlat (radian (- dest-lat src-lat))
+        dlon (radian (- dest-lon src-lon))
+        h-dlat (/ dlat 2)
+        h-dlon (/ dlon 2)
+        a (+
+            (pow (sin h-dlat) 2)
+            ( *
+              (cos (radian src-lat))
+              (cos (radian dest-lat))
+              (pow (sin h-dlon) 2)))
+        c (* 2
+             (atan2 (sqrt a)
+                    (sqrt (- 1 a))))]
+    (* earth-radius c)))
+