common: Implement TimeAndPos::distance_cm().
[gps-watch.git] / src / common / gps.rs
index 7e635fce6f37854a39ef9f81fe66dad60f3a02b4..85e1dd4a07d5d609fbdf3c1a59140c086e03c672 100644 (file)
@@ -63,6 +63,25 @@ impl TimeAndPos {
             longitude_rad: Fixed::from_i64(0),
         }
     }
+
+    pub fn distance_cm(&self, other: &TimeAndPos) -> i64 {
+        let a_lat = self.latitude_rad;
+        let a_lon = self.longitude_rad;
+
+        let b_lat = other.latitude_rad;
+        let b_lon = other.longitude_rad;
+
+        let x = (b_lon - a_lon) * ((b_lat + a_lat) / Fixed::from_i64(2)).cos();
+        let y = b_lat - a_lat;
+
+        let d_km = (x * x + y * y).sqrt() * Fixed::from_i64(6371);
+
+        let hundred = Fixed::from_i64(100);
+        let thousand = Fixed::from_i64(1000);
+
+        // Convert from km to cm.
+        (d_km * thousand * hundred).to_i64()
+    }
 }
 
 fn to_lower(c: u8) -> u8 {