Jose Bernhardt Jose Bernhardt - 10 days ago 6
Android Question

How to know when a position is front/back of another one in Maps

So I'm working in a project that needs a feature to identify when an object (in my case a car) is currently in front or behind another one using Google Maps.
I currently have the bearing (cars orientation) and the distance between both cars.

So far my approach is that if car2 has the same bearing as car1 and the distance between both cars is reducing, car1 gets an alert that car2 is behind. But, this only work if I'm in car1. car2 will also receive a false alarm saying that car1 is also behind him, wich is not true (car1 is on front). This is because I don't know which car is getting close to the other one due to the fact that I only have distance between them.

So the question is: Is there a way to know when a location is getting close to another one with the GPS and GoogleMaps? Maybe comparing Lat and Lon between both?

Answer

Calculate the bearing of the vector from one car (A) to another (B) (the code is here) and compare that to the bearing (direction of movement) of the "one car" A to calculate a relative direction.

relativeBearing = bearingToOtherCar - bearingOfThisCar;

If A is behind and B is in front then the relative direction from A to B is close to 0. In the opposite case it's close to 180. If B is on the left side it's 270 (or -90 if you like) and on the right side it's 90.

You just need handle the 359...0 transition properly when calculating the relative direction. If it's less than -180 then add 360 and if it's more than 180 then deduct it from 360:

if (relativeBearing < -180) relativeBearing = 360 + relativeBearing;
if (relativeBearing > 180) relativeBearing = 360 - relativeBearing;

This will give negative values for relative directions on the left side (-180...+180 scheme) and the values can be forced to the 0...359 scheme by adding 360 to any negative result.

Comments