Hi, I am new to swift and currently working on a project where I need to check if a given coordinate falls on a MKRoute or not. I searched a lot but unable to find a satisfied approach. Can someone help on this ?
how to check if a coordinate(CLLocationCoordinate2D) lies on a route using MapKit ?
I don't believe there is a method in MapKit to do this. You will need to implement it yourself.
Unless you need it to be very fast, a simple algorithm where you consider each segment of the route in turn will work OK.
Note that you will want to do an approximate match, i.e. find the closest distance from the point to the route and compare that with a threshold.
can you tell me how can one find the closest coordinate of the route from the given coordinate ?
Distance from a point to a line segment (pseudo-code):
a and b are the ends of the line segment
p is the point
let V = b - a
let W = p - a
let c1 = dot_product(V,W)
if (c1 <= 0) {
// a is the closest point to p
return magnitude(W)
} else {
let c2 = dot_product(V,V)
if (c2 <= c1) {
// b is the closest point to p
return magnitude(b-p)
} else {
let f = c1/c2
let q = a + f*V
// q is the closest point on the line ab to p
return magnitude(q-p)
}
}
My original reference for this method: http :// softsurfer.com/Archive/algorithm_0102/algorithm_0102.htm - but unfortunately is now 404s.
Obviously you need to do this for each segment of the route, and find the minimum distance.
P.S. don't post comments on this forum, post replies; I don't think it sends email alerts for comments.
P.S.
I should have said that you can't just use latitude and longitude values with that code, for a couple of reasons: one degree of latitude is not the same distance as one degree of longitude, except at the equator, and bad things happen at the poles and in the middle of the Pacific.
The best thing to do is to convert from lat-lon to geocentric (xyz) coordinates first. Good news: the pseudo-code I posted works equally well for 3D geocentric coordinates as for 2D.
I've not tried it, it is only a principle suggestion.
- create a duplicate of the route
- add the point to test as a waypoint (extra stop)
- compute the new driving time.
- if equal, waypoint was on the route.
See this: https://www.raywenderlich.com/10028489-routing-with-mapkit-and-core-location
@endecotp i will definitely use 3D geocentric coordinates now. Thanks for the idea.