I'm working with Google Maps SDK for iOS.
My project requires the ability of moving the current location marker by x meters along the pre-determined path drawn on to the map view. Therefore I've implemented the following method from this question(the answer by Koray Birand):
func distance(distance: Double, AwayFromCoordinate origin: CLLocationCoordinate2D, WithBearing bearing: Double) -> CLLocationCoordinate2D {
let earthRadius = 6372797.6 // in meters
let radianDistance = distance / earthRadius
let radianBearing = bearing * M_PI / 180.0
let latitude = origin.latitude * M_PI / 180
let longitude = origin.longitude * M_PI / 180
let lat2 = asin(sin(latitude) * cos(radianDistance) + cos(latitude) * sin(radianDistance) * cos(radianBearing))
let lon2 = longitude + atan2(sin(radianBearing) * sin(radianDistance) * cos(latitude), cos(radianDistance) - sin(longitude) * sin(lat2))
return CLLocationCoordinate2DMake(lat2 * 180 / M_PI, lon2 * 180 / M_PI)
}
So if I call the above method like the following:
currentLocationMarker.position = distance(0.5, AwayFromCoordinate: currentLocationMarker.position, WithBearing: bearing)
This yields me a new location 0.5 meters away from the current location.
However there is a slight problem that the movement starts to deflect a little like below even though the starting point is the same:
I couldn't figure out why such a deflection happens and not goes straight. Any ideas?
I believe you got this solution from this answer, right? If so, notice that when calculating the
lon2
you do:now take a look at the original answer's code:
And notice the last bit:
...- sin(lat1) * sin(lat2))
which in your code instead of latitudes uses one latitude and one longitude:...- sin(longitude) * sin(lat2))
So probably the right solution would be:
Perhaps this is the source of the problem??
I hope it helps =)