Skip to content
This repository has been archived by the owner on Feb 28, 2024. It is now read-only.

Commit

Permalink
geo: rewrite distanceTo calucaltion using math (not android impl)
Browse files Browse the repository at this point in the history
  • Loading branch information
hrach committed Oct 23, 2019
1 parent f8486cc commit df86820
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions src/main/java/com/sygic/travel/sdk/places/model/geo/LatLng.kt
Original file line number Diff line number Diff line change
@@ -1,29 +1,32 @@
package com.sygic.travel.sdk.places.model.geo

import android.location.Location
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import java.io.Serializable
import java.math.RoundingMode
import kotlin.math.PI
import kotlin.math.asin
import kotlin.math.cos
import kotlin.math.sqrt

@Parcelize
data class LatLng(
val lat: Double,
val lng: Double
) : Parcelable, Serializable {
/**
* Returns the approximate shortest distance to the point in meters. Uses WGS84 ellipsoid.
* Returns the approximate shortest distance to the point in meters. Uses Haversine_formula.
*/
fun distanceTo(point: LatLng): Float {
val results = floatArrayOf(0f, 0f, 0f)
Location.distanceBetween(
lat,
lng,
point.lat,
point.lng,
results
)
return results[0]
fun distanceTo(point: LatLng): Double {
// see https://stackoverflow.com/a/21623206/859688
// https://en.wikipedia.org/wiki/Haversine_formula
val lat1 = lat
val lon1 = lng
val lat2 = point.lat
val lon2 = point.lng
val p = PI / 180
val a = 0.5 - cos((lat2 - lat1) * p) / 2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos((lon2 - lon1) * p)) / 2
return 12742 * asin(sqrt(a))
}

fun withPrecision(decimals: Int = 6): LatLng {
Expand Down

0 comments on commit df86820

Please sign in to comment.