在给定设备位置和半径的情况下生成随机LatLng



我正试图在地图上给定位置附近生成随机点。我有一个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循环的目的只是确保获得最近的随机点,正如我所看到的,随着半径的增加,点会脱离圆圈。您可以删除循环。

这个答案应该会有所帮助。它看起来就像你把半径从米转换成度的execpt。

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

请参阅此处的链接。

相关内容

  • 没有找到相关文章

最新更新