gpt4 book ai didi

android - 给定设备位置和半径生成随机 LatLng

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:57:34 24 4
gpt4 key购买 nike

我正在尝试在 map 上的给定位置附近生成随机点。我有一个 circle 形状,它围绕着用户位置,半径为 100,我想在这个圆区域内生成随机的 LatLng 坐标。到目前为止,我已经想出了以下功能,但是点标记仍然出现在圆圈范围之外。

    double lat = location.getLatitude();
double lon = location.getLongitude();

for (int i = 0; i < markers.size(); i++) {
Marker mrk = markers.get(i);

Random random = new Random();


double radiusInDegrees =mCircle.getRadius();

double u = random.nextDouble();
double v = random.nextDouble();
double w = radiusInDegrees * Math.sqrt(u);
double t = 2 * Math.PI * v;
double x = w * Math.cos(t);
double y = w * Math.sin(t);

// Adjust the x-coordinate for the shrinking of the east-west distances
double new_x = x / Math.cos(lat);

double newLongitude = new_x + lon;
double newLatitude = y + lat;


mrk.setPosition(new LatLng(newLatitude,newLongitude));

}

最佳答案

借助于此 https://gis.stackexchange.com/a/68275

我能够制作一个函数,在一定半径内生成随机 LatLng 点,其中半径以米为单位。

public LatLng getRandomLocation(LatLng point, int radius) {

List<LatLng> randomPoints = new ArrayList<>();
List<Float> randomDistances = new ArrayList<>();
Location myLocation = new Location("");
myLocation.setLatitude(point.latitude);
myLocation.setLongitude(point.longitude);

//This is to generate 10 random points
for(int i = 0; i<10; i++) {
double x0 = point.latitude;
double y0 = point.longitude;

Random random = new Random();

// Convert radius from meters to degrees
double radiusInDegrees = radius / 111000f;

double u = random.nextDouble();
double v = random.nextDouble();
double w = radiusInDegrees * Math.sqrt(u);
double t = 2 * Math.PI * v;
double x = w * Math.cos(t);
double y = w * Math.sin(t);

// Adjust the x-coordinate for the shrinking of the east-west distances
double new_x = x / Math.cos(y0);

double foundLatitude = new_x + x0;
double foundLongitude = y + y0;
LatLng randomLatLng = new LatLng(foundLatitude, foundLongitude);
randomPoints.add(randomLatLng);
Location l1 = new Location("");
l1.setLatitude(randomLatLng.latitude);
l1.setLongitude(randomLatLng.longitude);
randomDistances.add(l1.distanceTo(myLocation));
}
//Get nearest point to the centre
int indexOfNearestPointToCentre = randomDistances.indexOf(Collections.min(randomDistances));
return randomPoints.get(indexOfNearestPointToCentre);
}

for 循环的目的只是为了确保获得最近的随机点,因为我已经看到点在我增加半径时偏离圆圈。您可以删除循环。

关于android - 给定设备位置和半径生成随机 LatLng,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33976732/

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