5

Possible Duplicate:
How to calculate distance between two locations using their longitude and latitude value

Before you all give me some education on how the earth is not a perfect sphere and it all changes when you get closer to the poles, which seems to be all I can find on the net. And before asking my father who is an accomplished geographer and my uncle who is a Quantum Physicist who works for NASA and me being a lowly computer programmer, I’d like to ask you guys first!

I only need a ball park Km distance as the crow flies from a phone to a list of pre populated locations for an area of 720 square kilometers, so variations are not important.

This is me right now, please don’t drop anything on me.

mLatitude=-38.3533177
mLongitude=144.9127674

And this is me ten minutes ago approximately 3kms away as the crow flies,

mLatitude=-38.3444385
mLongitude=144.9374762

How do I calculate that to get 3km?

I’m quite new to Java so I’m not sure what built in Math functions are available and I have no idea what the calculation is?

Cheers,

Mike.

Community
  • 1
  • 1

2 Answers2

27

You can use distanceTo() method of Location class to get distance between two locatins.

anujprashar
  • 6,263
  • 7
  • 52
  • 86
  • DistanceTo() and DistanceBetween () are kind of elusive, if I type them into a search I get results for mathematical equations that do what you would think they as built in functions should do. They as Nostras has said all have a slightly different earth radius, but for me I only need a ball park. –  Dec 18 '11 at 09:33
  • OK, you are saying you dont know how to use this method? – anujprashar Dec 18 '11 at 10:08
5
public class Calculator {
    private static final int earthRadius = 6371;
    public static float calculateDistance(float lat1, float lon1, float lat2, float lon2)
    {
        float dLat = (float) Math.toRadians(lat2 - lat1);
        float dLon = (float) Math.toRadians(lon2 - lon1);
        float a =
                (float) (Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1))
                        * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2));
        float c = (float) (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)));
        float d = earthRadius * c;
        return d;
    }
}
nostra13
  • 12,377
  • 3
  • 33
  • 43