如何在圆形范围内的 android 地图上生成标记

How to spawn markers on android map inside a circular range

我正在尝试制作一个 pokemonGo 风格的应用程序。 我曾尝试使用纬度和经度公式来计算标记(口袋妖怪)应该产生的坐标范围,但我只设法得到一个矩形区域。我想在玩家周围的圆形区域生成它们,我该怎么做?

这是我计算矩形面积的代码。

        Random r = new Random();
        int randomDistanceLatitude = r.nextInt(range*2) - range;
        r = new Random();
        int randomDistanceLongitude = r.nextInt(range*2) - range;


        double latitudeDegreeToAdd = 1.7 * randomDistanceLatitude * 0.000009043717329571146924;
        double longitudeDegreeToAdd = randomDistanceLongitude * (1 / (111320 * Math.cos(infoLocal.getLastKnownLocation().getLatitude())));

        LatLng enemy1Location = new LatLng(infoLocal.getLastKnownLocation().getLatitude() + latitudeDegreeToAdd, infoLocal.getLastKnownLocation().getLongitude() + longitudeDegreeToAdd);

        enemies[i] = mMap.addMarker(new MarkerOptions().position(enemy1Location).title("Monster").snippet("Click to Attack!").icon(BitmapDescriptorFactory.fromResource(R.drawable.enemy3)).anchor(0.5f, 0.5f));

好像是一道数学题。

圆的公式是 (x, y) = (cos(angle) * rX, sin(angle) * rY) + (centerX, centerY)

因此,代码将如下所示。

Random r = new Random();
double radius = r.nextFloat() * range; // or r.nextDouble()...
double angle = r.nextFloat() * 2.0f * Math.PI;
double randomDistanceLatitude = Math.cos(angle) * radius;
double randomDistanceLongitude = Math.sin(angle) * radius;
...

由于 lat lng 不在笛卡尔坐标系中,它不是一个纯圆,但我认为 range 在这个用例中足够小,可以忽略这种失真。


补充说明。

如果mMap表示Google Maps地图,您可能对Google Maps - Shape - Circle

感兴趣