Maven坐标
<dependency>
<groupId>org.gavaghan</groupId>
<artifactId>geodesy</artifactId>
<version>1.1.3</version>
</dependency>
坐标实体
@Data
public class GeoPoint {
private double latitude;
private double longitude;
public GeoPoint(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
}
工具类
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
public class GeoUtils {
public static double getDistanceMeter(GeoPoint geoPoint1, GeoPoint geoPoint2) {
GlobalCoordinates gpsFrom = new GlobalCoordinates(geoPoint1.getLongitude(), geoPoint1.getLatitude());
GlobalCoordinates gpsTo = new GlobalCoordinates(geoPoint2.getLongitude(), geoPoint2.getLatitude());
GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.WGS84, gpsFrom, gpsTo);
return geoCurve.getEllipsoidalDistance();
}
public static GeoPoint getNearestPointToCenter(GeoPoint center, GeoPoint[] points) {
double minDistance = Double.MAX_VALUE;
GeoPoint nearestPoint = null;
for (GeoPoint point : points) {
double distance = GeoUtils.getDistanceMeter(center, point);
if (distance < minDistance) {
minDistance = distance;
nearestPoint = point;
}
}
return nearestPoint;
}
public static GeoPoint getCenterPoint(GeoPoint[] points) {
double latitude = 0;
for (GeoPoint point : points) {
latitude += point.getLatitude();
}
latitude /= points.length;
double longitude = 0;
for (GeoPoint point : points) {
longitude += point.getLongitude();
}
longitude /= points.length;
return new GeoPoint(latitude, longitude);
}
}
测试
public static void main(String[] args) {
GeoPoint[] points = new GeoPoint[]{
new GeoPoint(39.939123, 116.395645),
new GeoPoint(39.929456, 116.393645),
new GeoPoint(39.959789, 116.397645)};
GeoPoint center = getCenterPoint(points);
System.out.println(center);
GeoPoint nearestPoint = getNearestPointToCenter(center, points);
System.out.println(nearestPoint);
double distance = getDistanceMeter(center, nearestPoint);
System.out.println(distance);
}