Google Maps Javascript - computeHeading and compass direction to calculate direction of facing

8.4k views Asked by At

Using the computeHeading() function against my currentPosition and a destinationPosition i can get the angle returned (tis currently between -180 and +180).

heading = google.maps.geometry.spherical.computeHeading(
    currentLocation,
    destinationLocation
);

I can get the direction of the compass also using a function to return the alpha which gives me angle of rotation from north.

alpha = null;
//Check for iOS property
if (event.webkitCompassHeading) {
    //window.confirm("iOS device - using webKit instead"); // report back that we are indeed on iOS
    alpha = event.webkitCompassHeading;
}
//non iOS
else {
    alpha = event.alpha;
}

var locationIcon = myLocationMarker.get('icon');
locationIcon.rotation = 360 - alpha;
myLocationMarker.set('icon', locationIcon);

This gives me the angle and then helps me rotate my icon so i can see if im pointing the correct way

Can someone tell me the math/js code to then get the way i'm facing against the destination to give me a returned result. I need to know if i'm facing the destination and then i can see if im facing the wrong way etc.

Im going to try to use some panning of web audio to help direct people to point the right way.

Thank you

edit: here is an image to maybe help clarify. Im sure its a simple calculation but i cant figure it outenter image description here

2

There are 2 answers

2
kaho On

I think it is just math, since..

diff(Lat)/diff(lng) = tan(alpha)

then I guess you can figure out the rest?

note that since heading can change radically due to the GPS accuracy problem. Consider using both compass data and some kind of algorithms to ease the outliners.

0
Biranchi On

Calculate angle between two Latitude/Longitude points

private double angleFromCoordinate(double lat1, double long1, double lat2,
        double long2) {

    double dLon = (long2 - long1);

    double y = Math.sin(dLon) * Math.cos(lat2);
    double x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)
            * Math.cos(lat2) * Math.cos(dLon);

    double brng = Math.atan2(y, x);

    brng = Math.toDegrees(brng);
    brng = (brng + 360) % 360;
    brng = 360 - brng; // count degrees counter-clockwise - remove to make clockwise

    return brng;
}

=====================================================================

Using GoogleMap apis:

<script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=geometry"></script>

var point1 = new google.maps.LatLng(lat1, lng1);
var point2 = new google.maps.LatLng(lat2, lng2);
var heading = google.maps.geometry.spherical.computeHeading(point1,point2);