0

I am currently writing a tracking app that is able to get your currently facing angle and the angle to a destination and point an arrow in the direction you need to travel. (As the crow flies)

I am having trouble taking these 2 angles and making them work together so that the arrow points in the correct direction.

My knowledge of Mathematics is extremely limited so any help would be appreciated.

function deviceOrientationListener(event) {
        facing = Math.round(event.alpha);
        deg = bearing(lat, lng, getUrlVars()["lat"], getUrlVars()["long"]);
        finaldeg = facing - deg;
        c.innerHTML = '<img style="-ms-transform: rotate(' + finaldeg + 'deg);-webkit-transform: rotate(' + finaldeg + 'deg);transform: rotate(' + finaldeg + 'deg);" src="images/arrow.png" />';
}

The finaldeg is what i am having trouble with working out.

Mattigins
  • 1,014
  • 9
  • 25

1 Answers1

0

I did like this with Ionic and the plugin cordova-plugin-device-orientation

  • to_turn is the variable in which I record the computed angle
  • degreeStyle is the style applied to the arrow shown on end-user's screen
  • last_lat/last_lng is the current position of the user
  • target_lat/target_lng is the destination

`

this.destinationBearing = this.bearing(  
                                        this.last_lat,
                                        this.last_lng,
                                        this.target_lat, 
                                        this.target_lng);

this.compass = this.deviceOrientation.watchHeading().subscribe(
    (data: DeviceOrientationCompassHeading) => {
        this.currentHeading = data.trueHeading;
        if (this.destinationBearing > this.currentHeading) {
            this.to_turn = this.destinationBearing - this.currentHeading;
        } else {
            this.to_turn =  360 - (this.currentHeading - this.destinationBearing);
        }
        this.degreeStyle = 'rotate(' + this.to_turn + 'deg)';
    }
);


bearing(startLat, startLng, destLat, destLng){
    startLat = this.toRadians(startLat);
    startLng = this.toRadians(startLng);
    destLat = this.toRadians(destLat);
    destLng = this.toRadians(destLng);
    let y = Math.sin(destLng - startLng) * Math.cos(destLat);
    let x = Math.cos(startLat) * Math.sin(destLat) -
    Math.sin(startLat) * Math.cos(destLat) * Math.cos(destLng - startLng);
    let brng = Math.atan2(y, x);
    brng = this.toDegrees(brng);
    return (brng + 360) % 360;
}

toRadians(degrees) {
    return degrees * Math.PI / 180;
};

toDegrees(radians) {
    return radians * 180 / Math.PI;
}
Pierre
  • 1,044
  • 15
  • 27