半径范围内随机经纬度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
private static final double EARTH_RADIUS = 6372.796924;

public static GpsInfo getRandomLocation(GpsInfo center, double distance) {
if (distance <= 0) distance = 50;
double lat, lon, brg;
distance = distance / 1000;
GpsInfo location = new GpsInfo();
double maxdist = distance;
maxdist = maxdist / EARTH_RADIUS;
double startlat = rad(center.getLat());
double startlon = rad(center.getLon());
double cosdif = Math.cos(maxdist) - 1;
double sinstartlat = Math.sin(startlat);
double cosstartlat = Math.cos(startlat);
double dist;
double rad360 = 2 * Math.PI;
dist = Math.acos((new Random().nextDouble() * cosdif + 1));
brg = rad360 * new Random().nextDouble();
lat = Math.asin(sinstartlat * Math.cos(dist) + cosstartlat * Math.sin(dist) * Math.cos(brg));
lon = deg(normalizeLongitude(startlon * 1 + Math.atan2(Math.sin(brg) * Math.sin(dist) * cosstartlat, Math.cos(dist) - sinstartlat * Math.sin(lat))));
lat = deg(lat);

location.setLat(padZeroRight(lat));
location.setLon(padZeroRight(lon));
return location;
}

static double rad(double d) {
return d * Math.PI / 180.0;
}

static double deg(double rd) {
return (rd * 180 / Math.PI);
}

static double normalizeLongitude(double lon) {
double n = Math.PI;
if (lon > n) {
lon = lon - 2 * n;
} else if (lon < -n) {
lon = lon + 2 * n;
}
return lon;
}

static double padZeroRight(double s) {
double sigDigits = 8;
s = Math.round(s * Math.pow(10, sigDigits)) / Math.pow(10, sigDigits);
return s;
}