0

How can I get the direction of travel (N, NE, E, SE, S, SW, W, NW) on an iPhone using only information from the GPS (longitude and latitude)?

I do not want to use the compass because it isn't always accurate.

Christian Gossain
  • 5,702
  • 12
  • 49
  • 85
  • Did you know that GPS isn't always accurate either? – Gabe Dec 27 '10 at 06:35
  • You'd be surprised how accurate the GPS is. It's much more accurate than the Magnetometer, especially on the iPhone 4 and iPad. The compass has to deal with so much interference from the electronics around it. – Christian Gossain Dec 27 '10 at 06:37
  • Here's a question and answer about adding a category to CLLocation that easily calculates the bearing based only on a lat/lon pair: http://stackoverflow.com/questions/3925942/cllocation-category-for-calculating-bearing-w-haversine-function – Matthew Frederick Dec 27 '10 at 08:46

1 Answers1

2

Just grab the current coordinates at two separate instants and subtract them. Here's some pseudocode (sorry, I don't speak Objective-C):

start <- get current position
wait some time
end <- get current position
direction = end - start

This will give you a vector that points in the current direction. To get it as an angle you can use the vector dot product.

product <- start.lat * end.lat + start.lng * end.lng
start_length <- sqrt(start.lat^2 + start.lng^2)
end_length <- sqrt(end.lat^2 + end.lng^2)
angle <- arccos(product/(start_length * end_length))

Given the angle, you can easily get the cardinal direction. Just see which one is nearest.

R. Martinho Fernandes
  • 209,766
  • 68
  • 412
  • 492