standardize-geolocation
Version:
takes geolocations of different formats and outputs a standardized version
116 lines (95 loc) • 3 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
function createPoint(rawLatitude, rawLongitude, rawElevation) {
const latitude = maybeGetNumber(rawLatitude);
if (latitude === undefined) {
throw new TypeError('`latitude` is required but not found');
}
if (latitude > 90 || latitude < -90) {
throw new RangeError('`latitude` should be between -90 and 90');
}
const longitude = maybeGetNumber(rawLongitude);
if (longitude === undefined) {
throw new TypeError('`longitude` is required but not found');
}
if (longitude > 180 || longitude < -180) {
throw new RangeError('`longitude` should be between -180 and 180');
}
const elevation = maybeGetNumber(rawElevation);
return {
elevation,
latitude,
longitude
};
}
function getElevation(point) {
if ('elevation' in point) {
return point.elevation;
} else if ('alt' in point) {
return point.alt;
} else if ('altitude' in point) {
return point.altitude;
} else if ('elev' in point) {
return point.elev;
}
}
function getLatitude(point) {
if ('latitude' in point) {
return point.latitude;
} else if ('lat' in point) {
return point.lat;
}
}
function getLongitude(point) {
if ('longitude' in point) {
return point.longitude;
} else if ('lng' in point) {
return point.lng;
} else if ('lon' in point) {
return point.lon;
} else if ('long' in point) {
return point.long;
}
}
function isGeoJSONPoint(point) {
return 'coordinates' in point && point.type === 'Point';
} // HACK: This is a workaround for TypeScript not properly narrowing readonly arrays
function isArray(array) {
return Array.isArray(array);
}
function maybeGetNumber(value) {
const valueAsNumber = Number(value);
return isNaN(valueAsNumber) ? undefined : valueAsNumber;
}
function standardizeGeolocation(point) {
if (isArray(point)) {
// Geolocation points must have 2 or 3 elements
if (point.length !== 2 && point.length !== 3) {
throw new TypeError('point array must have exactly 2 or 3 numeric elements');
}
return createPoint(point[0], point[1], point[2]);
}
if (isGeoJSONPoint(point)) {
// GeoJSON points are in [longitude, latitude] order
return createPoint(point.coordinates[1], point.coordinates[0]);
}
if ('geometry' in point) {
return standardizeGeolocation(point.geometry);
}
if ('location' in point) {
return standardizeGeolocation(point.location);
}
if ('position' in point) {
return standardizeGeolocation(point.position);
}
const elevation = getElevation(point);
const latitude = getLatitude(point);
const longitude = getLongitude(point);
return createPoint(latitude, longitude, elevation);
}
exports.createPoint = createPoint;
exports["default"] = standardizeGeolocation;
exports.getElevation = getElevation;
exports.getLatitude = getLatitude;
exports.getLongitude = getLongitude;
exports.standardizeGeolocation = standardizeGeolocation;
;