Question

Given a starting latitude and longitude, bearing, and distance, I'm trying to calculate the coordinates of the ending location (in Android). So you're at x,y and facing in the direction of z degrees (radians, actually). If you move forward d meters, what will be your new location? I found a formula for doing this and here's my code:

private double[] move(Location location, float bearingRadians, double meters){
        // Formula from: http://www.movable-type.co.uk/scripts/latlong.html
        double lat1 = location.getLatitude();
        double lon1 = location.getLongitude();
    double distanceRadians = meters / EARTH_RADIUS_METERS;

    double newLat = Math.asin(Math.sin(lat1) * Math.cos(distanceRadians) + Math.cos(lat1) * Math.sin(distanceRadians) * Math.cos(bearingRadians));
    double newLon = lon1 + Math.atan2( Math.sin(bearingRadians) * Math.sin(distanceRadians) * Math.cos(lat1), Math.cos(distanceRadians) - Math.sin(lat1) * Math.sin(newLat));

    Log.d(TAG,"Bearing: " + bearingRadians + ", distance: " + meters);
    Log.d(TAG,"Latitude changed from " + lat1 + " to " + newLat);
    Log.d(TAG,"Longitude changed from " + lon1 + " to " + newLon);

    return new double[]{newLat,newLon};
}

Here's the output:

Bearing: -2.9843714, distance: 7.0
Latitude changed from 43.8 to -0.18229823611594947
Longitude changed from -103.05 to -103.05000017504125

(Note: not my actual location if you're curious!) Notice that the longitude changed very slightly, as I would expect since I'm only moving 7 meters. But what the heck happened to the latitude? I have tried converting the inputs and outputs to and from radians and degrees in case that's the issue but it's not. None of those conversions brings the latitude number anywhere near the range it should be.

The comment has the website where I got the formula, but there are lots of other places that have it, and I've checked the latitude formula against a bunch of them until my eyes hurt and I can't see any issue. Anybody see the problem?

Was it helpful?

Solution

I did not analyse where exactly the problem with your formula is hidden.

But if you are just looking for a working example, you can find Android code in the accepted answer of this SO question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top