Untitled

 avatar
unknown
kotlin
2 years ago
1.3 kB
3
Indexable
import kotlin.math.*

data class LatLng(val latitude: Double, val longitude: Double)

fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
    val earthRadius = 6371 // Radius of the Earth in kilometers
    val dLat = Math.toRadians(lat2 - lat1)
    val dLon = Math.toRadians(lon2 - lon1)
    val a = sin(dLat / 2) * sin(dLat / 2) +
            cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) *
            sin(dLon / 2) * sin(dLon / 2)
    val c = 2 * atan2(sqrt(a), sqrt(1 - a))
    val distance = earthRadius * c
    return distance
}

fun calculateRouteLength(route: List<LatLng>): Double {
    var totalDistance = 0.0

    for (i in 0 until route.size - 1) {
        val currentPoint = route[i]
        val nextPoint = route[i + 1]
        val distance = calculateDistance(
            currentPoint.latitude,
            currentPoint.longitude,
            nextPoint.latitude,
            nextPoint.longitude
        )
        totalDistance += distance
    }

    return totalDistance
}

// Example usage
val route = listOf(
    LatLng(40.7128, -74.0060), // New York City
    LatLng(34.0522, -118.2437), // Los Angeles
    LatLng(51.5074, -0.1278) // London
)

val routeLength = calculateRouteLength(route)
println("Route length: $routeLength km")