Advertisement
SimpleCookie

Untitled

Jan 13th, 2024
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 0.92 KB | None | 0 0
  1. import kotlin.math.*
  2.  
  3. fun calculateHaversineDistance(
  4.     lat1: Double, lon1: Double,
  5.     lat2: Double, lon2: Double
  6. ): Double {
  7.     val R = 6371 // Radius of the Earth in kilometers
  8.  
  9.     val dLat = Math.toRadians(lat2 - lat1)
  10.     val dLon = Math.toRadians(lon2 - lon1)
  11.  
  12.     val a = sin(dLat / 2) * sin(dLat / 2) +
  13.             cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) *
  14.             sin(dLon / 2) * sin(dLon / 2)
  15.  
  16.     val c = 2 * atan2(sqrt(a), sqrt(1 - a))
  17.  
  18.     return R * c // Distance in kilometers
  19. }
  20.  
  21. fun main() {
  22.     // Example coordinates for two points
  23.     val lat1 = 37.7749 // Latitude for point 1
  24.     val lon1 = -122.4194 // Longitude for point 1
  25.  
  26.     val lat2 = 34.0522 // Latitude for point 2
  27.     val lon2 = -118.2437 // Longitude for point 2
  28.  
  29.     val distance = calculateHaversineDistance(lat1, lon1, lat2, lon2)
  30.  
  31.     println("Distance between the two points: $distance kilometers")
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement