GeoLocationUtils { public static GeoLocation centralLocation(List<GeoLocation> geoLocations) { Objects.requireNonNull(geoLocations); if (geoLocations.isEmpty()) { return null; } int locationCount = geoLocations.size(); if (locationCount == 1) { return geoLocations.iterator().next(); } double x = 0; double y = 0; double z = 0; for (GeoLocation geoLocation : geoLocations) { double latitude = Math.toRadians(geoLocation.getLatitude()) * Math.PI / 180; double longitude = Math.toRadians(geoLocation.getLongitude()) * Math.PI / 180; x += Math.cos(latitude) * Math.cos(longitude); y += Math.cos(latitude) * Math.sin(longitude); z += Math.sin(latitude); } x = x / locationCount; y = y / locationCount; z = z / locationCount; double centralLongitude = Math.atan2(y, x); double centralSquareRoot = Math.sqrt(x * x + y * y); double centralLatitude = Math.atan2(z, centralSquareRoot); double midPointLatitude = Math.toDegrees(centralLatitude * 180 / Math.PI); double midPointLongitude = Math.toDegrees(centralLongitude * 180 / Math.PI); return new GeoLocation(midPointLatitude, midPointLongitude); } private  GeoLocationUtils(); static GeoLocation centralLocation(List<GeoLocation> geoLocations); static Address convertGeoCodeToAddress(InvertGeoCodeAddress resultAddress, User user,
												  GeoLocation location, UserInterfaceType interfaceType, boolean makePrimary); static String locationFilterSuffix(String locationEntityLabel); static void addLocationParamsToQuery(Query query, GeoLocation location, Integer radiusInMetres); final static int DEFAULT_RADIUS; }
@Test public void testCenterCalculation1() { ArrayList<GeoLocation> locations = Lists.newArrayList( new GeoLocation(50.00, 40.00), new GeoLocation(70.00, 40.00), new GeoLocation(70.00, 40.00) ); GeoLocation centralLocation = GeoLocationUtils.centralLocation(locations); assertEquals(63.33, centralLocation.getLatitude(), 0.01); assertEquals(40, centralLocation.getLongitude(), 0.001); }
@Test public void testCenterCalculation2() { List<GeoLocation> locations = new ArrayList<>(); locations.add(new GeoLocation(121.612016711363d, 32)); locations.add(new GeoLocation(121.849004871905, 31)); GeoLocation centralLocation = GeoLocationUtils.centralLocation(locations); assertEquals(121.73, centralLocation.getLatitude(), 0.001); assertEquals(31.5, centralLocation.getLongitude(), 0.1); }
@Test public void testCenterCalculationWithEmptyInput() { GeoLocation centralLocation = GeoLocationUtils.centralLocation(Collections.emptyList()); assertNull(centralLocation); }