Skip to content

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.

1°=60′=3600″1° = 60′ = 3600″

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.

43.040833°=43°+2′×1°60′+27″×1°3600″43.040833° = 43° + 2′ \times \frac{1°}{60′} + 27″ \times \frac{1°}{3600″}

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. π\pi radians equal 180 degrees:

π rad=180°\pi \text{ rad} = 180°

So an angle in degrees is the angle in radians times 180° divided by π\pi, and the reverse:

αdegrees=αradians×180°παradians=αdegrees×π180°\alpha_{\text{degrees}} = \alpha_{\text{radians}} \times \frac{180°}{\pi} \qquad \alpha_{\text{radians}} = \alpha_{\text{degrees}} \times \frac{\pi}{180°}

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 (xc,yc)(x_c, y_c) and a point (xp,yp)(x_p, y_p) follows from the Pythagorean theorem:

d=(xp−xc)2+(yp−yc)2d = \sqrt{(x_p - x_c)^2 + (y_p - y_c)^2}

The point is inside the circle of radius rr if d<rd < r, on the circle if d=rd = r, and outside if d>rd > r. You can skip the square root by comparing d2d^2 with r2r^2 instead, that is, compare (xp−xc)2+(yp−yc)2(x_p - x_c)^2 + (y_p - y_c)^2 with r2r^2.

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.

a=sin⁡2(Δφ2)+cos⁡φ1⋅cos⁡φ2⋅sin⁡2(Δλ2)a = \sin^2\left(\frac{\Delta\varphi}{2}\right) + \cos\varphi_1 \cdot \cos\varphi_2 \cdot \sin^2\left(\frac{\Delta\lambda}{2}\right)

c=2⋅atan2⁡(a,1−a)c = 2 \cdot \operatorname{atan2}\left(\sqrt{a}, \sqrt{1 - a}\right)

d=R⋅cd = R \cdot c

Here φ\varphi is latitude, λ\lambda is longitude and RR 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:

d=arccos⁡(sin⁡φ1⋅sin⁡φ2+cos⁡φ1⋅cos⁡φ2⋅cos⁡Δλ)⋅Rd = \arccos\left(\sin\varphi_1 \cdot \sin\varphi_2 + \cos\varphi_1 \cdot \cos\varphi_2 \cdot \cos\Delta\lambda\right) \cdot R

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) ) * 6371000

If 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) ) * 6371000

Distance 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) * R
Expression<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));
}

References

Related notes

28 min readTürkçe

Solidity

Solidity ile Ethereum akıllı sözleşmeleri: türler, fonksiyonlar, veri konumları, ether transferi, kalıtım ve interface örnekleri.

  • Miscellaneous
2 min read

LaTeX and KaTeX

Recompile LaTeX documents automatically with latexmk, and write and render maths on web pages with KaTeX.

  • Miscellaneous

Type to search the whole site.