Вопрос

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.

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.

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.

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);
}

and the code for rotateCompass:

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);
}

I'm almost certain my rotation code works because when I replace

rotateCompass(rotation - degreesClockwiseFromNorth);

with

rotateCompass(0 - degreesClockwiseFromNorth);

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.

Thanks for reading, any suggestions or corrections are appreciated.

Это было полезно?

Решение

Your math is all screwed up because the distance between 2 degrees of longitude is not the same as 2 degrees of latitude. In fact, it isn't even a constant length for longitude- its shorted by the poles and longest at the equator. Use the Location.distanceTo functions instead.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top