Calculating distance using latitude longitude coordinates in kilometers with Java

荒凉一梦 提交于 2019-12-01 04:44:20

问题


I have following method that that calculates distance and returns it in miles:

public static int calcDistance(float latA, float longA, float latB, float longB) {

    double theDistance = (Math.sin(Math.toRadians(latA)) *
            Math.sin(Math.toRadians(latB)) +
            Math.cos(Math.toRadians(latA)) *
            Math.cos(Math.toRadians(latB)) *
            Math.cos(Math.toRadians(longA - longB)));

    return new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09).intValue();
}

What needs to be changed in order for this method to return kilometers?

And what other ways of calculating the distance between A and B are there?

(preferably in java code)


回答1:


You only need to change the last line to:

return new Double((Math.toDegrees(Math.acos(theDistance))) * 
    69.09*1.6093).intValue();

1 mile = 1.6093 kilometer




回答2:


Since that formula returns a result in miles, just convert from miles to kilometers

kilometers = miles * 1.609344



回答3:


I believe you are looking for the haversine formula: http://www.movable-type.co.uk/scripts/latlong.html

The formula is multiplied by the radius of earth, which determines the resulting units.




回答4:


You could change your code to say

return new Double((Math.toDegrees(Math.acos(theDistance))) * 111.12).intValue();

equivalent to the conversions already expressed.

There are alternate and better formulae for calculating distances given latitude and longitude. Lambert's formula seems excellent, giving an accuracy of 10 meters over distances of thousands of kilometers, and uses some of the code you've already provided.




回答5:


The distance you are computing is based on Earth as a sphere, which may be good for comparing approximate --short-- distances. For better results on longer distances (air travel, for example), I would recommend a Geospatial Utility library (such as the open source GeoTools) to take things into consideration like the Ellipsoid nature of the Earth's shape.

Many professional-grade Geo solutions use WGS-84 as the model, which GeoTools support.

Remember -- getting 100 decimal places of "accuracy" doesn't count if your assumptions are wrong! ;)



来源:https://stackoverflow.com/questions/5557706/calculating-distance-using-latitude-longitude-coordinates-in-kilometers-with-jav

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