Geographic coordinates (geo)
geo works with latitude/longitude coordinates: distances, bearings, routes, bounds, polygon membership, coordinate text and unit conversion. Import from "geo". These operations use geographic degrees and metres.
Coordinates and units
Coordinate is a copyable value with public latitude: f64 and longitude: f64. Latitude is in [-90, 90], longitude in [-180, 180]. isValidCoordinate checks those ranges. Validate external input before using distance or polygon operations; constructing a Coordinate does not validate it.
GeoJSON positions use longitude first. fromGeoJSON([longitude, latitude]) converts that order to named fields; toGeoJSON(point) returns [f64; 2] in GeoJSON order. A numeric coordinate has no altitude or coordinate reference system tag. Convert other projections before passing them to this package.
Distances are metres, areas square metres and speeds metres per second. convertDistance, convertArea and convertSpeed convert those base units to the requested enum variant. For example, convertDistance(1000.0, DistanceUnit.Kilometer) is 1.0. Prefer the enum overloads for configuration: unknown distance/area unit strings panic, while unknown speed strings leave the input unchanged.
Measure a journey
This complete program checks coordinate order, spherical distance and unit conversion without files or network access.
import { Coordinate, fromGeoJSON, isValidCoordinate,
getDistance, getPreciseDistance, DistanceUnit, convertDistance } from "geo";
fn main() {
let start = Coordinate { latitude: 0.0, longitude: 0.0 };
let finish = fromGeoJSON([1.0, 0.0]);
if !isValidCoordinate(finish) { $panic("invalid coordinate"); }
let metres = getDistance(start, finish);
if metres != 111319.0 { $panic("unexpected rounded distance"); }
let kilometres = convertDistance(metres, DistanceUnit.Kilometer);
if kilometres < 111.0 || kilometres > 112.0 { $panic("wrong units"); }
match getPreciseDistance(start, finish, 0.0) {
Some(distance) => {
if distance < 111000.0 || distance > 112000.0 {
$panic("unexpected ellipsoid distance");
}
},
None => { $panic("distance did not converge"); },
}
$println("geo distance: PASS");
}getDistance uses a spherical Haversine calculation. Its two-argument form rounds to the nearest metre; the third accuracy argument controls rounding, and 0.0 leaves the result unrounded. That argument is an output rounding increment, not a guarantee of measurement accuracy.
getPreciseDistance uses the WGS84 Vincenty inverse calculation and returns Option<f64>: None means its iteration did not converge. Decide explicitly whether your application can fall back to spherical distance. Do not turn None into zero, which would incorrectly identify distinct points as coincident.
TimedCoordinate { coordinate, time } stores time in milliseconds. getSpeed(start, end) divides distance by elapsed time and returns metres per second. Require a finite, positive elapsed interval before calculating speed.
Work with a region
import { Coordinate, getBounds, isPointInBoundingBox,
isPointInPolygon, wktToPolygon } from "geo";
fn main() {
let polygon = match wktToPolygon("POLYGON ((0 0, 2 0, 2 2, 0 2, 0 0))") {
Some(points) => points,
None => { $panic("invalid polygon text"); },
};
let point = Coordinate { latitude: 1.0, longitude: 1.0 };
let bounds = match getBounds(&polygon) {
Some(value) => value,
None => { $panic("empty polygon"); },
};
if !isPointInBoundingBox(point, bounds) { $panic("outside bounds"); }
if !isPointInPolygon(point, &polygon) { $panic("outside polygon"); }
$println("geo region: PASS");
}WKT positions also use longitude first. wktToPolygon returns an owning Vec<Coordinate> for the exterior ring only; it discards holes and extra dimensions. It is not a complete WKT geometry/schema validator. Validate the returned coordinates and your application's minimum point count for external input. Polygon membership uses ray crossings; choose an explicit boundary policy if points on an edge have business meaning.
getBounds takes component-wise extrema and returns None for an empty collection. getBoundsOfDistance(point, metres) creates a spherical-radius box. isPointInBoundingBox includes its boundary and treats minLng > maxLng as an antimeridian crossing. A component-wise box from an arbitrary point set is not necessarily the smallest box across that meridian.
Choose the operation
| Task | API and result |
|---|---|
| Distance along a route | getPathLength(&points): f64; sums adjacent segments |
| Nearest coordinate | findNearest(origin, &points): Option<Coordinate> |
| Preserve application records | findNearestIndex / orderByDistanceIndices with a coordinate callback |
| Reorder coordinates | orderByDistance returns an owning vector |
| Spherical centre | getCenter(&points): Option<Coordinate> |
| Centre of component bounds | getCenterOfBounds(&points): Option<Coordinate> |
| Bearing | getGreatCircleBearing / getRhumbLineBearing; degrees |
| Compass label | getCompassDirection; a borrowed direction label |
| Destination from bearing | computeDestinationPoint(point, metres, bearing) |
| Radius membership | isPointWithinRadius; strict distance comparison |
| Segment proximity | getDistanceFromLine, isPointNearLine, isPointInLine |
| Polygon area | getAreaOfPolygon; spherical square metres |
| Arc intersection | getIntersectionOfLines: unique crossing of two finite minor great-circle arcs, or None |
| Degree/minute/second text | sexagesimalToDecimal, decimalToSexagesimal, coordinateFromText |
Collection operations also accept distance callbacks. For application records, provide a fn(&T): Coordinate extractor and keep the returned indices associated with the same unchanged vector. This avoids copying records merely to sort by distance.
Dynamic coordinate input
The package also accepts arrays, vectors and maps. Numeric maps use coordinateFromMap(&Map<string, f64>); text-map and value-map overloads convert their values before range checking. Coordinate-key helpers recognize aliases such as latitude/longitude and allow caller-supplied key lists. Use the checked conversion result instead of selecting an arbitrary missing key as 0.0.
fromGeoJSON(&Vec<f64>) can return None when two components are unavailable. Fixed-array overloads require sufficient coordinates. A returned coordinate still needs the validation appropriate to its conversion overload. Borrowed map/vector inputs remain owned by the caller; returned numeric coordinates are independent copyable values.
See collections, string conversion and Unicode for the surrounding data-processing pipeline.