Moving GMSMarker by X Meters Deflects

2019-09-14 14:29发布

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:

Path being drawn as deflected

I couldn't figure out why such a deflection happens and not goes straight. Any ideas?

1条回答
爷、活的狠高调
2楼-- · 2019-09-14 14:46

I believe you got this solution from this answer, right? If so, notice that when calculating the lon2you do:

let lon2 = longitude + atan2(sin(radianBearing) * sin(radianDistance) * cos(latitude), 
cos(radianDistance) - sin(longitude) * sin(lat2))

now take a look at the original answer's code:

let lon2 = lon1 + atan2(sin(rbearing) * sin(distRadians) * cos(lat1), 
cos(distRadians) - sin(lat1) * sin(lat2))

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:

let lon2 = longitude + atan2(sin(radianBearing) * sin(radianDistance) * cos(latitude), 
cos(radianDistance) - sin(latitude) * sin(lat2))

Perhaps this is the source of the problem??

I hope it helps =)

查看更多
登录 后发表回答