Android calculate distance between two locations [duplicate]

时光怂恿深爱的人放手 提交于 2019-12-18 05:04:22

问题


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.


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/8550674/android-calculate-distance-between-two-locations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!