Petre Popescu
Petre Popescu

Reputation: 2002

Direction between two geolocation points

I need to calculate the direction between two geolocation points (lat and log defined). I don't really need the entire angle (I found something like this), but only N, NE, E, SE, S, SW, W, NW is fine.

Any help is appreciated

Upvotes: 0

Views: 732

Answers (3)

jcxavier
jcxavier

Reputation: 2232

Well, assuming you are getting a value in degrees from 0º to 360º, you could use a simple method like:

String[] coordNames = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" };

// assuming this value comes from somewhere else
int degrees = val;

degrees %= 360;
degrees /= 45;

String coord = coordNames[degrees];

This won't give you correct approximate values, as you might notice. 0º to 44º will give you N, 45º to 89º will give you NE, and so on.

Hopefully it will get you on the right track!

Upvotes: 0

njzk2
njzk2

Reputation: 39406

You can use Location.bearingTo ( http://developer.android.com/reference/android/location/Location.html#bearingTo%28android.location.Location%29 )

Create 2 location objects from your points, and you can get a precise bearing. Then you simply compare it to the 8 values. (like between -22.5 and +22.5 it's N, until 67.5 it's NE, until 112.5 it's E, and so on)

Upvotes: 3

John
John

Reputation: 16007

If they're short distances, you can approximate by taking the lats/longs as is, and calculating the angle through atan2(y,x) where y is the latitude and x is the longitude. Convert the resulting angle to N, NE, SW, etc. Just be careful around the international date line.

Upvotes: 0

Related Questions