GIS calculations
Geographic math for developers: degrees and minutes, radius searches, great-circle distance and the midpoint of several points, with Java code.
5 min readUpdated
Location features in business applications (“find sellers within 10 km”, “centre the map on these points”) need a small set of geographic formulas. This note covers coordinate notation, the point-in-circle test, great-circle distance with the haversine formula and the spherical law of cosines (including a JPA Criteria API version), and the geographic midpoint of several points.
All formulas treat the earth as a sphere with a mean radius of 6,371 km. The spherical model is accurate to about 0.3 %, which is enough for search radii and map views.
Convert degrees, minutes and seconds
Latitude and longitude are given in degrees (°). Longitude runs over 360° (180° E to 180° W) and latitude over 180° (90° N to 90° S). Each degree divides into 60 minutes (′) and each minute into 60 seconds (″); finer precision uses decimal fractions of a second. This base-60 notation is called sexagesimal.
For example, a spot in upstate New York is at 43°2′27″ N, 77°14′30.60″ W. In decimal degrees that is 43.040833° N, 77.241833° W: divide the minutes by 60, the seconds by 3600, and add both to the degrees.
In signed decimal notation, south latitudes and west longitudes are negative, so the point above is stored as 43.040833, -77.241833.
Convert between radians and degrees
Trigonometric functions in Java, SQL and spreadsheets expect radians. radians equal 180 degrees:
So an angle in degrees is the angle in radians times 180° divided by , and the reverse:
In Java, use Math.toRadians and Math.toDegrees.
Check whether a point is inside a circle
On a flat plane, the distance between the centre and a point follows from the Pythagorean theorem:
The point is inside the circle of radius if , on the circle if , and outside if . You can skip the square root by comparing with instead, that is, compare with .
This works for screen or projected coordinates. Latitude and longitude are angles on a sphere, so for a radius search on the earth, compute the great-circle distance below and compare it with the radius.
Calculate the distance between two points
The haversine formula gives the great-circle distance between two points: the shortest distance over the earth’s surface, “as the crow flies”, ignoring elevation.
Here is latitude, is longitude and is the earth’s radius (mean radius 6,371 km). All angles must be in radians.
The spherical law of cosines is shorter. With 64-bit floating point it gives well-conditioned results down to distances of a few metres:
The same formula in a spreadsheet, giving metres. If the cells hold radians:
=ACOS( SIN(lat1)*SIN(lat2) + COS(lat1)*COS(lat2)*COS(lon2-lon1) ) * 6371000If the cells hold degrees:
=ACOS( SIN(lat1*PI()/180)*SIN(lat2*PI()/180) + COS(lat1*PI()/180)*COS(lat2*PI()/180)*COS(lon2*PI()/180-lon1*PI()/180) ) * 6371000Distance in a JPA Criteria query
To find rows within a radius in the database, build the spherical law of cosines as a Criteria API expression. In this example the entity PointofinterestEntity stores its coordinates in radians (latitudeRadian, longitudeRadian), so the database does not have to convert them on every row. The second point comes from the request; radiusKilometers is the search radius.
Expression<Double> earthRadiusKilometers = cb.literal(6371.0);
Expression<Double> lat1 = pointofinterest.get(PointofinterestEntity_.latitudeRadian);Expression<Double> lon1 = pointofinterest.get(PointofinterestEntity_.longitudeRadian);Expression<Double> lat2 = cb.literal(rfp.getPointofinterest().getLatitudeRadian());Expression<Double> lon2 = cb.literal(rfp.getPointofinterest().getLongitudeRadian());
// sin(lat1) * sin(lat2)Expression<Double> sinProduct = cb.prod( cb.function("SIN", Double.class, lat1), cb.function("SIN", Double.class, lat2));
// cos(lat1) * cos(lat2) * cos(lon2 - lon1)Expression<Double> cosProduct = cb.prod( cb.prod(cb.function("COS", Double.class, lat1), cb.function("COS", Double.class, lat2)), cb.function("COS", Double.class, cb.diff(lon2, lon1)));
// d = acos(sinProduct + cosProduct) * RExpression<Double> distance = cb.prod( cb.function("ACOS", Double.class, cb.sum(sinProduct, cosProduct)), earthRadiusKilometers);
Predicate withinRadius = cb.le(distance, radiusKilometers);cb.function calls the database’s own SIN, COS and ACOS functions, so the calculation runs in SQL. Combine withinRadius with the query’s other predicates in cb.and(...).
Note: Rounding can push the ACOS argument slightly above 1 when both points are the same, which returns NULL or an error depending on the database. If that matters, clamp the argument or use the haversine formula.
Calculate the midpoint of several points
The geographic midpoint (also called the geographic centre or centre of gravity) of several points is not the average of their latitudes and longitudes. Convert each point to 3D Cartesian coordinates, average those, and convert the result back.
This method uses Point2D.Double with x as latitude and y as longitude, both in degrees. Every point has the same weight; to weight points, for example by the time spent at each, multiply each point’s coordinates by its weight and divide by the total weight.
/** * Geographic midpoint of two or more points on the earth's surface. * Method: https://www.geomidpoint.com/calculation.html * * @param points latitude in x, longitude in y, both in degrees * @return the midpoint, or null if it is undefined (for example two antipodal points) */public static Point2D.Double midpoint(List<Point2D.Double> points) { double totalWeight = 0; double xt = 0; double yt = 0; double zt = 0;
for (Point2D.Double point : points) { // Convert latitude and longitude from degrees to radians double lat = Math.toRadians(point.x); double lon = Math.toRadians(point.y);
// Convert to Cartesian coordinates on the unit sphere double xn = Math.cos(lat) * Math.cos(lon); double yn = Math.cos(lat) * Math.sin(lon); double zn = Math.sin(lat);
// Weight of this point; 1 for an unweighted midpoint double wn = 1;
totalWeight += wn; xt += xn * wn; yt += yn * wn; zt += zn * wn; }
// Weighted average of the x, y and z coordinates double x = xt / totalWeight; double y = yt / totalWeight; double z = zt / totalWeight;
// If the average is (almost) the centre of the earth, there is no meaningful midpoint double epsilon = 1e-9; if (Math.abs(x) < epsilon && Math.abs(y) < epsilon && Math.abs(z) < epsilon) { return null; }
// Convert the average back to latitude and longitude. // Excel's ATAN2 takes its arguments in reverse order: ATAN2(x, y) instead of atan2(y, x). double lon = Math.atan2(y, x); double hyp = Math.sqrt(x * x + y * y); double lat = Math.atan2(z, hyp);
return new Point2D.Double(Math.toDegrees(lat), Math.toDegrees(lon));}