Sadako
Sadako

Reputation: 352

Calculate the direction of an object with geographical coordinates (latitude, longitude)

I have the coordinates of a player and another object. Both are with geographical coordinates (Latitude and longitude). I have also the direction in what the player is facing (compass). How can I calculate the angle to the other object from the player direction? e.g. I want to know if the object is to the right/left of the player and how many degrees.

Thanks a lot!

Upvotes: 2

Views: 4510

Answers (3)

mctylr
mctylr

Reputation: 5169

With a few it depends, the answer is in essence, you want to know about how to do geographic navigation. One of the reasons it depends is that the distances involve as well as the accuracy needed may influence the answer.

For short distances (<10km) you may be able to ignore the curvature of the Earth, and treat it like a two dimensional Cartesian map (latitude / longitude as X-Y). Then you question becomes basic trigonometry.

For larger distances, or improved accuracy, you can either approximate using an spheroid model of the Earth (assume the Earth is a perfect sphere, which it is not) and calculate the Great Circle bearing and distance.

Or you can model the Earth as an ellipsoid, and calculate its geographic navigation.

Two web pages that may help: Details for computing distance using lat/long coordinates and Calculate distance, bearing and more between Latitude/Longitude points.

Note: atan2 and Haversine formula are often useful implementation details.

Small added note: bearing is a synonym for heading or direction in this context.

Upvotes: 5

FunkTheMonk
FunkTheMonk

Reputation: 10938

There are tools in the API to do this for you: Location.bearingTo(Location) and GeomagneticSensor will give you the direction from your position to the target - which you can then adjust based off the devices current heading.

If you've already got a MapView running & are lazy, set up a MyLocationOverlay, enableCompass and skip the GeomagneticSensor and let the MapView do it for you.

Upvotes: 0

divestoclimb
divestoclimb

Reputation: 793

You need this spherical trig formula: http://williams.best.vwh.net/avform.htm#Crs Once you have the course (angle relative to true north), you can subtract off the compass heading of the direction the player is facing to get the relative heading.

(I don't know if Android automatically compensates for magnetic variation or not, but if not you'll have to account for it too to get the angle right in all areas)

Upvotes: 2

Related Questions