Library to provide basic geospatial operations like distance calculation, conversion of decimal coordinates to sexagesimal and vice versa, etc.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Functions for validating coordinates, format detection, and other utility operations.
Validates coordinate objects and values to ensure they contain valid geospatial data.
/**
* Validate coordinate format and value ranges
* @param point - Coordinate to validate (object or array format)
* @returns True if coordinate is valid, false otherwise
*/
function isValidCoordinate(point: GeolibInputCoordinates): boolean;Usage Examples:
import { isValidCoordinate } from "geolib";
// Validate different coordinate formats
console.log(isValidCoordinate({ lat: 51.515, lng: 7.453 })); // true
console.log(isValidCoordinate({ latitude: 51.515, longitude: 7.453 })); // true
console.log(isValidCoordinate([7.453, 51.515])); // true (GeoJSON)
// Invalid coordinates
console.log(isValidCoordinate({ lat: 95, lng: 7.453 })); // false (lat > 90)
console.log(isValidCoordinate({ lat: 51.515, lng: 185 })); // false (lng > 180)
console.log(isValidCoordinate({ lat: "invalid", lng: 7.453 })); // false
// Validation in data processing
const coordinates = [
{ lat: 51.515, lng: 7.453 },
{ lat: 95, lng: 7.453 }, // Invalid
{ lat: 51.520, lng: 7.460 },
{ lat: 51.510, lng: 190 } // Invalid
];
const validCoords = coordinates.filter(isValidCoordinate);
console.log(validCoords); // Only valid coordinatesValidates latitude values and formats.
/**
* Validate latitude value and format
* @param latitude - Latitude value to validate (number or string)
* @returns True if latitude is valid (-90 to 90), false otherwise
*/
function isValidLatitude(latitude: any): boolean;Usage Examples:
import { isValidLatitude } from "geolib";
// Valid latitudes
console.log(isValidLatitude(51.515)); // true
console.log(isValidLatitude(-89.999)); // true
console.log(isValidLatitude(90)); // true
console.log(isValidLatitude("45.123")); // true (string numbers)
// Invalid latitudes
console.log(isValidLatitude(91)); // false (> 90)
console.log(isValidLatitude(-91)); // false (< -90)
console.log(isValidLatitude("invalid")); // false
console.log(isValidLatitude(null)); // falseValidates longitude values and formats.
/**
* Validate longitude value and format
* @param longitude - Longitude value to validate (number or string)
* @returns True if longitude is valid (-180 to 180), false otherwise
*/
function isValidLongitude(longitude: any): boolean;Usage Examples:
import { isValidLongitude } from "geolib";
// Valid longitudes
console.log(isValidLongitude(7.453)); // true
console.log(isValidLongitude(-179.999)); // true
console.log(isValidLongitude(180)); // true
console.log(isValidLongitude("-123.456")); // true (string numbers)
// Invalid longitudes
console.log(isValidLongitude(181)); // false (> 180)
console.log(isValidLongitude(-181)); // false (< -180)
console.log(isValidLongitude("invalid")); // false
console.log(isValidLongitude(undefined)); // falseFunctions to detect coordinate format types.
/**
* Test if value is in decimal coordinate format
* @param value - Value to test
* @returns True if value is decimal format, false otherwise
*/
function isDecimal(value: any): boolean;
/**
* Test if value is in sexagesimal (DMS) coordinate format
* @param value - Value to test
* @returns True if value is sexagesimal format, false otherwise
*/
function isSexagesimal(value: any): boolean;Usage Examples:
import { isDecimal, isSexagesimal } from "geolib";
// Test coordinate formats
console.log(isDecimal(51.515)); // true
console.log(isDecimal("51.515")); // true
console.log(isDecimal("51° 30′ 54″")); // false
console.log(isSexagesimal("51° 30′ 54″ N")); // true
console.log(isSexagesimal("51° 30.9′ E")); // true
console.log(isSexagesimal(51.515)); // false
// Format detection for parsing
function parseCoordinate(value: string | number) {
if (isDecimal(value)) {
return parseFloat(value.toString());
} else if (isSexagesimal(value)) {
return sexagesimalToDecimal(value.toString());
} else {
throw new Error("Unknown coordinate format");
}
}
console.log(parseCoordinate(51.515)); // 51.515
console.log(parseCoordinate("51° 30′ 54″ N")); // 51.515Calculates speed between two timestamped coordinates.
/**
* Calculate speed between two timestamped coordinates
* @param start - Starting coordinate with timestamp
* @param end - Ending coordinate with timestamp
* @param distanceFn - Optional distance function (default: getDistance)
* @returns Speed in meters per second
*/
function getSpeed(
start: GeolibInputCoordinatesWithTime,
end: GeolibInputCoordinatesWithTime,
distanceFn?: (
from: GeolibInputCoordinates,
to: GeolibInputCoordinates
) => number
): number;
interface GeolibInputCoordinatesWithTime extends GeolibInputCoordinates {
time: number; // Unix timestamp in milliseconds
}Usage Examples:
import { getSpeed, getPreciseDistance, convertSpeed } from "geolib";
// Calculate vehicle speed from GPS tracking
const position1 = {
latitude: 51.515,
longitude: 7.453,
time: 1640995200000 // Unix timestamp in milliseconds
};
const position2 = {
latitude: 51.520,
longitude: 7.460,
time: 1640995260000 // 60 seconds later
};
const speedMps = getSpeed(position1, position2);
console.log(`Speed: ${speedMps.toFixed(2)} m/s`);
const speedKmh = convertSpeed(speedMps, "kmh");
console.log(`Speed: ${speedKmh.toFixed(1)} km/h`);
// Using high-precision distance
const preciseSpeed = getSpeed(position1, position2, getPreciseDistance);
console.log(`Precise speed: ${preciseSpeed.toFixed(3)} m/s`);
// GPS tracking analysis
const gpsTrack = [
{ lat: 51.515, lng: 7.453, time: 1640995200000 },
{ lat: 51.516, lng: 7.454, time: 1640995230000 }, // 30s later
{ lat: 51.517, lng: 7.455, time: 1640995260000 }, // 30s later
{ lat: 51.518, lng: 7.456, time: 1640995290000 } // 30s later
];
const speeds = [];
for (let i = 1; i < gpsTrack.length; i++) {
const speed = getSpeed(gpsTrack[i-1], gpsTrack[i]);
const speedKmh = convertSpeed(speed, "kmh");
speeds.push(speedKmh);
}
console.log("Segment speeds:", speeds.map(s => `${s.toFixed(1)} km/h`));
// Average speed calculation
const avgSpeed = speeds.reduce((a, b) => a + b, 0) / speeds.length;
console.log(`Average speed: ${avgSpeed.toFixed(1)} km/h`);Additional utilities for working with coordinate data in applications.
/**
* Earth radius constant in meters
*/
const earthRadius: number; // 6378137
/**
* Coordinate bounds constants
*/
const MINLAT: number; // -90
const MAXLAT: number; // 90
const MINLON: number; // -180
const MAXLON: number; // 180
/**
* Regular expression for parsing sexagesimal coordinates
*/
const sexagesimalPattern: RegExp;
/**
* Arrays of valid coordinate property names
*/
const longitudeKeys: string[]; // ['lng', 'lon', 'longitude', 0]
const latitudeKeys: string[]; // ['lat', 'latitude', 1]
const altitudeKeys: string[]; // ['alt', 'altitude', 'elevation', 'elev', 2]Usage Examples:
import {
earthRadius,
MINLAT,
MAXLAT,
MINLON,
MAXLON,
longitudeKeys,
latitudeKeys
} from "geolib";
// Custom coordinate validation
function isValidLatRange(lat: number): boolean {
return lat >= MINLAT && lat <= MAXLAT;
}
function isValidLngRange(lng: number): boolean {
return lng >= MINLON && lng <= MAXLON;
}
// Find coordinate properties in object
function findCoordinateKeys(obj: any): { lat?: string, lng?: string } {
const result: { lat?: string, lng?: string } = {};
for (const key of Object.keys(obj)) {
if (latitudeKeys.includes(key)) {
result.lat = key;
}
if (longitudeKeys.includes(key)) {
result.lng = key;
}
}
return result;
}
const coord = { latitude: 51.515, longitude: 7.453 };
const keys = findCoordinateKeys(coord);
console.log(keys); // { lat: 'latitude', lng: 'longitude' }
// Use earth radius for custom calculations
function customCircumference(): number {
return 2 * Math.PI * earthRadius;
}
console.log(`Earth circumference: ${customCircumference()} meters`);