Last active
January 21, 2020 22:14
-
-
Save truedem/e0d142c95af5d582d93f0b8d5937ff6a to your computer and use it in GitHub Desktop.
How close is the geo-location to the path?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.reddit.com/r/androiddev/comments/ert88w/asking_if_this_is_possible_to_do_with_maps_api/ | |
fun closestDistance(point:LatLng, route:Polyline) : Double { | |
var minDist = Double.MAX_VALUE | |
for (i in 0 until (route.points?.size ?: 0) - 1) { | |
val dist=lineDistance(point,route.points[i],route.points[i+1]) | |
if (dist<minDist){ | |
minDist=dist | |
} | |
} | |
//minDist is in degrees, 111319.9 is meters per degree at the equator. | |
return minDist * 111319.9 | |
} | |
private fun lineDistance(point: LatLng, pathA: LatLng, pathB: LatLng) : Double { | |
val x=point.latitude | |
val y=point.longitude | |
val x1=pathA.latitude | |
val y1=pathA.longitude | |
val x2=pathB.latitude | |
val y2=pathB.longitude | |
val A = x - x1 | |
val B = y - y1 | |
val C = x2 - x1 | |
val D = y2 - y1 | |
val dot = A * C + B * D | |
val len_sq = C * C + D * D | |
var param = -1.0 | |
if (len_sq != 0.0) //in case of 0 length line | |
param = dot / len_sq | |
val (xx,yy)=if (param < 0) { | |
Pair(x1,y1) | |
} | |
else if (param > 1) { | |
Pair(x2,y2) | |
} | |
else { | |
Pair(x1 + param * C,y1 + param * D) | |
} | |
val dx = x - xx; | |
val dy = y - yy; | |
return Math.sqrt(dx * dx + dy * dy) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment