Search code examples
javascriptionic-frameworkhybrid-mobile-appcompass-geolocation

how to direct an arrow on top of compass to point towards specific direction. for e.g. current position to Saudi Arabia


I am creating an Ionic 4 app with angular and I want to create a compass which would direct towards specific direction. That direction will be presented by an arrow above the compass. So far I have created the compass and compass is working fine and placed an arrow above it. Screen shot of app.enter image description here

What I know is that i have to calculate an angle from current position to target position.I have used some stack overflow solutions to find angle and use that angle to point arrow to desired location. But unfortunately I can't get my desired angle.

This is the code to determine the angle.

  angleFromCoordinate() {
    let lat1 = this.latCoords
    let lon1 = this.lngCoords
    let lat2 = this.destLat;
    let lon2 = this.destLong;
    var p1 = {
      x: lat1,
      y: lon1
    };

    var p2 = {
      x: lat2,
      y: lon2
    };
    var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;
    console.log(angleDeg);
    return angleDeg;
  }

I also want the arrow to move along if the device is rotated. I am rotating my compass with ionic 4's plugin deviceOrientation

  this.deviceSubscription = this.deviceOrientation.watchHeading().subscribe(
      (data: DeviceOrientationCompassHeading) => {
        //to torate compass
        this.rotateCompass(data.magneticHeading);
        //to rotate the arrow
        this.rotateArrow(data.magneticHeading);
      }
    );

Solution

  • I got it working alright. I just want to make it clear if anyone is in search of the solution to this problem that the above mention code for getting the angle from one point to an other point is working fine. Code to get angle.

    angleFromCoordinate() {
        let lat1 = this.latCoords
        let lon1 = this.lngCoords
        let lat2 = this.destLat;
        let lon2 = this.destLong;
        var p1 = {
          x: lat1,
          y: lon1
        };
    
        var p2 = {
          x: lat2,
          y: lon2
        };
        var angleDeg = Math.atan2(p2.y - p1.y, p2.x - p1.x) * 180 / Math.PI;
        console.log(angleDeg);
        return angleDeg;
      }
    

    This method returns the angle and you can use this angle to point your compass to your desired location.