Search code examples
androidgpscompass-geolocation

Having a GPS location and my GPS location, ¿how to calculate the direction (0-360º from north) to the location from my location?


I tried to do with BearingTo(), but i don't know how to use it. myLocation.bearingTo(BuildingLocation) gives me 0º if i am facing the Building and North direction, gives me 90º if i am facing the Building and East Direction, gives me -180º if i am facing the Building and South direction. Then bearingTo doesn't works for my needs.

I need to do that because i need to calculate when the phone camera is facing the object...


Solution

  • Try this link: http://www.movable-type.co.uk/scripts/latlong.html

    Edit-- This would be the example, use locations or get the long/lat in other ways

        Location destination;
        Location from;
    
        double dLon = Math.abs(destination.getLongitude()-from.getLongitude()); //Delta Longitude
    
        double y = Math.sin(dLon) * Math.cos(destination.getLatitude());
        double x = Math.cos(from.getLatitude())*Math.sin(destination.getLatitude()) -
                Math.sin(from.getLatitude())*Math.cos(destination.getLatitude())*Math.cos(dLon);
        double brng = Math.atan2(y, x);
        double brngdegrees = Math.toDegrees(brng);