Units¶
The units
module contains utilities for working with units of measure, like
Length,
Area,
Rotation, and
Bearing.
Details can be found in the API reference.
Installation¶
commonMain {
dependencies {
implementation("org.maplibre.spatialk:units:0.4.0")
}
}
dependencies {
implementation("org.maplibre.spatialk:units-jvm:0.4.0")
}
Simple unit conversion¶
In Kotlin, Length
, Area
, and Rotation
are type-safe value classes wrapping
a Double
. They can be converted to and from raw Double
values using the
provided unit accessors.
In Java, use the convert
helper from
org.maplibre.spatialk.units.extensions.Utils
to convert between units.
val distance: Length = 123.miles
println(distance.inKilometers)
val area: Area = 45.acres
println(area.inSquareMeters)
double distanceKm = convert(123.0, Miles, Kilometers);
System.out.println(Kilometers.format(distanceKm, 2));
double areaSqM = convert(45.0, Acres, SquareMeters);
System.out.println(SquareMeters.format(areaSqM, 2));
Arithmetic¶
In Kotlin, Area
and Length
support arithmetic operations through operator
overloading, converting between scalars, lengths, and areas as needed.
val manhattanBlock: Area = (1.miles / 20.0) * (1.miles / 7.0)
val chicagoBlock: Area = 330.feet * 660.feet
val ratio: Double = manhattanBlock / chicagoBlock
Bearings and Rotations¶
Bearing
represents an absolute geographic heading (e.g., North, East), while
Rotation
represents a relative angular displacement. In Kotlin, bearings can
be rotated using operators, and the difference between two bearings is a
rotation.
val heading: Bearing = Bearing.North
val turnedRight: Bearing = heading + 90.degrees
val turnedLeft: Bearing = heading - 45.degrees
val diff: Rotation = turnedRight - turnedLeft
Custom units¶
Predefined SI (International System of Units) and Imperial units are available, but you can define custom units as needed.
// how many football fields could fit on the earth's oceans?
val americanFootballField = AreaUnit(109.728 * 48.8, "football fields")
val earthRadius: Length = 6371.kilometers
val earthSurface: Area = 4 * PI * earthRadius * earthRadius
val oceanSurface: Area = 0.7 * earthSurface
val result = oceanSurface.roundToLong(americanFootballField)
// how many football fields could fit on the earth's oceans?
AreaUnit AmericanFootballField = new AreaUnit(109.728 * 48.8, "football fields");
double earthRadiusM = convert(6371.0, Kilometers, Meters);
double earthSurfaceSqM = 4 * Math.PI * earthRadiusM * earthRadiusM;
double oceanSurfaceSqM = 0.7 * earthSurfaceSqM;
double result = convert(oceanSurfaceSqM, SquareMeters, AmericanFootballField);