kab*_*178 4 android google-maps android-maps-v2
我试图在给定位置附近的地图上生成随机点.我有一个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));
}
Run Code Online (Sandbox Code Playgroud)
借助此 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);
}
Run Code Online (Sandbox Code Playgroud)
for循环的目的只是为了确保获得最近的随机点,因为我已经看到当我增加半径时,点已经离开圆圈.你可以删除循环.
这个答案应该有帮助。它看起来就像您所要做的,只是将半径从米转换为度。
// Convert radius from meters to degrees
double radiusInDegrees = radius / 111000f;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3979 次 |
| 最近记录: |