Snap userLocation to MKPolyline (MapKit & Swift)

I'm working on a navigation app and I would like to snap the userLocation to the MKRoute's Polyline much like how Apple does in Apple Maps. I've added the route's MKPolyline to my MKMapView and it looks great, the user's location is just usually not centered on the road or is off to the side a bit even when using kCLLocationAccuracyBestForNavigation as the CLLocationManager's accuracy. I need it to be centered like Apple Maps as shown bellow.

How would I go about doing this? Is there a way to snap MKAnnotation's to roads (or MKPloylines) and update with the CLLocationManager's userLocation?

It's a year later, but I've completed something similar. First of all nothing like that exists in MapKit - you'll need to do this yourself. Here's a high-level overview.

  1. Take the coordinates that make up your polyline and create a new array of coordinates, based on your original list, that's 'chunked' into 10 meter segments. If you're getting your original coordinates from MKRequest or another directions provider, the coordinates will be 'optimised' so will look this this:

O------O---O--------O-----O

And you want this: O-O-O-O-O-O-O-O-O-O-O-O

Creating a list of coordinates that have a distance of 10 meters from each other, based on your original list, should be simple enough.

  1. Find the nearest point in the new coordinate list to the user location.

Iterate over each coordinate in your new list and use the Haversine formula to find the distance between the user's location and that coordinate. The shortest distance wins.

  1. Place your custom 'user location arrow/dot' at that coordinate.

This will look like the user location is on the polyline. Bonus points for 'snapping away' from the polyline if the user veers too far away from the poly line.

Snap userLocation to MKPolyline (MapKit & Swift)
 
 
Q