gpt4 book ai didi

android - 计算两个位置之间的距离(以米为单位)

转载 作者:太空宇宙 更新时间:2023-11-03 12:03:45 25 4
gpt4 key购买 nike

我有两个位置,我想以米为单位计算距离。我写了一些代码,但效果不佳。

private void getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2)
{
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);

Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);

int R = 6371; // km

double dLat = deg2rad(lat2-lat1);
double dLon = deg2rad(lon2-lon1);
double a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double distanceInMeters = R * c;
Log.e("distanceInMeters",distanceInMeters/10000+"mm");
}

public double deg2rad(double deg) {
return deg * (Math.PI/180);
}

如何计算以米为单位的距离?我的目标是,如果 meter > 200 做某事。我该如何解决我的问题?

最佳答案

无需为此重新发明轮子。

您可以只使用 Location.distanceBetween() 方法。

来自 the documentation :

Computes the approximate distance in meters between two locations

这是一个简单的例子:

private float getDistanceBetweenTwoPoints(double lat1,double lon1,double lat2,double lon2) {

float[] distance = new float[2];

Location.distanceBetween( lat1, lon1,
lat2, lon2, distance);

return distance[0];
}

如果结果数组不仅仅填充了索引零,则每个其他索引都包含一个方位角(初始和最终)。

方位角是指定罗盘方向的数字。

来自 http://www.geomidpoint.com/destination/help.html :

The bearing (or azimuth) is the compass direction to travel from the starting point, and must be within the range 0 to 360. 0 represents north, 90 is east, 180 is south and 270 is west.

关于android - 计算两个位置之间的距离(以米为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43080343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com