title: Android, using gps and compass to point towards coordinate
body: <p>I'm trying to make an app that points you toward a position. You press a button and it stores the gps coordinates, then calculates things like distance and the angle you need to face. Then it leads you back to that remembered position by "pointing" toward it using an onscreen compass graphic.</p>
  
  <p>At least, it's supposed to. After messing with the code for hours, I've come to the conclusion that there's just a logic error somewhere due to my lack of trig practice over the past few years.</p>
  
  <p>The compass and GPS position are updated fairly frequently. This is the code in my main update call for the user interface that rotates the compass and displays the distance.</p>
  
  <pre><code>public void updateUI(){
      double deltaX = targetLongitude - currentLongitude;
      double deltaY = targetLatitude - currentLatitude;
      double distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));
      double rotation = Math.toDegrees(Math.atan2(deltaX,deltaY));
      distanceTextView.setText(Double.toString(distance));
      rotateCompass(rotation - degreesClockwiseFromNorth);
  }
  </code></pre>
  
  <p>and the code for rotateCompass:</p>
  
  <pre><code>public void rotateCompass(double degrees){
      degrees -= currentRotation; //calculates necessary rotation across updates
      currentRotation += degrees;
  
      matrix.postRotate(
          (float) degrees, 
          compass.getDrawable().getBounds().width() / 2,
          compass.getDrawable().getBounds().height() / 2);
  
      compass.setImageMatrix(matrix);
  }
  </code></pre>
  
  <p>I'm almost certain my rotation code works because when I replace</p>
  
  <pre><code>rotateCompass(rotation - degreesClockwiseFromNorth);
  </code></pre>
  
  <p>with</p>
  
  <pre><code>rotateCompass(0 - degreesClockwiseFromNorth);
  </code></pre>
  
  <p>it points north right alongside a real compass regardless of the direction I'm facing. But when I use the former, it points towards a consistent point, but that point seems to be nowhere near the target point. 
  So I've come to the conclusion my error is either in calculating the correct angle, or expecting the gps to be too precise. I haven't tested it for distances further than what I can in my backyard, but I assume that if it was a gps accuracy issue I'd see my compass jumping all over the place rather than adamantly pointing in a wrong direction.</p>
  
  <p>Thanks for reading, any suggestions or corrections are appreciated.</p>