Package Exports
- @masaajid/qibla
Readme
๐งญ Qibla Direction Library
A comprehensive TypeScript library for calculating precise Qibla direction using proven geodetic algorithms. Provides accurate bearing calculations to the Kaaba in Mecca from any location worldwide with optional magnetic declination corrections.
โจ Features
- ๐ฏ Precise Geodetic Calculations - Great circle bearing calculations using proven mathematical algorithms
- ๐งญ Basic Magnetic Declination - Optional simplified magnetic bearing approximation for compass use
- ๐ Flexible Coordinate Input - Support for various coordinate formats and elevation data
- ๐ง Configurable Precision - Adjustable precision for bearing and distance calculations
- ๐ฑ TypeScript First - Complete type safety with excellent IntelliSense
- ๐ Efficient Calculations - Fast geodetic computations with standard algorithms
- ๐ Global Coverage - Accurate calculations from any location worldwide
- ๐งช Thoroughly Validated - Tested against multiple reference implementations
๐ Quick Start
Installation
# Using Bun (recommended)
bun add @masaajid/qibla
# Using npm
npm install @masaajid/qibla
# Using yarn
yarn add @masaajid/qiblaBasic Usage
import { getQiblaDirection } from "@masaajid/qibla";
// Basic qibla calculation
const location = { latitude: 40.7589, longitude: -73.9851 }; // New York
const qibla = getQiblaDirection(location);
console.log(qibla);
// {
// bearing: 58.49, // Degrees from true north
// distance: 11011.2, // Distance to Kaaba in kilometers
// from: { latitude: 40.7589, longitude: -73.9851 },
// to: { latitude: 21.422487, longitude: 39.826206 }
// }Enhanced Usage with Compass Features
import { calculateQiblaWithCompass } from "@masaajid/qibla";
// Enhanced calculation with cardinal directions
const result = calculateQiblaWithCompass(location, {
includeCardinalDirection: true,
includeMagneticDeclination: true,
bearingPrecision: 2,
distancePrecision: 1,
});
console.log(result);
// {
// bearing: 58.49,
// distance: 11011.2,
// from: { latitude: 40.7589, longitude: -73.9851 },
// to: { latitude: 21.422487, longitude: 39.826206 },
// cardinalDirection: "NE",
// description: "Northeast",
// magneticDeclination: -13.2,
// magneticBearing: 45.29
// }๐ API Reference
Core Functions
getQiblaDirection(coordinates, options?)
Main function for calculating qibla direction with optional configuration.
Parameters:
coordinates: Location coordinates (see coordinate formats below)options?: Optional calculation configuration
Returns: QiblaResult with bearing, distance, and coordinate information
calculateQibla(coordinates, options?)
Basic qibla calculation function.
Returns: QiblaResult with essential qibla information
calculateQiblaWithCompass(coordinates, options?)
Enhanced calculation with compass features like cardinal directions and magnetic declination.
Returns: EnhancedQiblaResult with additional compass information
Coordinate Formats
The library accepts flexible coordinate input formats:
// Object format
const coords1 = { latitude: 40.7589, longitude: -73.9851 };
// Array format
const coords2 = [40.7589, -73.9851];
// With elevation (ignored for qibla calculations)
const coords3 = { latitude: 40.7589, longitude: -73.9851, elevation: 10 };Configuration Options
interface QiblaConfig {
bearingPrecision?: number; // Decimal places for bearing (default: 2)
distancePrecision?: number; // Decimal places for distance (default: 1)
includeCardinalDirection?: boolean; // Include cardinal direction (N, NE, etc.)
includeMagneticDeclination?: boolean; // Include magnetic declination correction
}Utility Functions
import {
calculateBearing,
calculateDistance,
getCardinalDirection,
getDirectionDescription,
isAtKaaba,
KAABA_COORDINATES
} from '@masaajid/qibla';
// Calculate bearing between any two points
const bearing = calculateBearing(from, to);
// Calculate distance between coordinates
const distance = calculateDistance(coord1, coord2);
// Get cardinal direction from bearing
const cardinal = getCardinalDirection(58.5); // Returns "NE"
// Get human-readable description
const description = getDirectionDescription(58.5); // Returns "Northeast"
// Check if at Kaaba location
const atKaaba = isAtKaaba(coordinates, tolerance?);
// Access Kaaba coordinates
console.log(KAABA_COORDINATES); // { latitude: 21.422487, longitude: 39.826206 }๐ง Advanced Features
Precision Configuration
Control the precision of calculations based on your needs:
const result = getQiblaDirection(coordinates, {
bearingPrecision: 4, // 4 decimal places: 58.4923ยฐ
distancePrecision: 0, // Whole kilometers: 11011 km
});Magnetic Declination
Get magnetic bearing for compass navigation (basic approximation):
const result = calculateQiblaWithCompass(coordinates, {
includeMagneticDeclination: true,
});
console.log(`True bearing: ${result.bearing}ยฐ`);
console.log(`Magnetic bearing: ${result.magneticBearing}ยฐ`);
console.log(`Declination: ${result.magneticDeclination}ยฐ`);Note: The magnetic declination is a simplified approximation. For precise compass navigation, use specialized magnetic declination services.
Cardinal Directions
Get user-friendly direction descriptions:
const result = calculateQiblaWithCompass(coordinates, {
includeCardinalDirection: true,
});
console.log(`Direction: ${result.cardinalDirection}`); // "NE"
console.log(`Description: ${result.description}`); // "Northeast"Location Validation
The library includes comprehensive coordinate validation:
import { QiblaValidationError } from "@masaajid/qibla";
try {
const result = getQiblaDirection({ latitude: 91, longitude: 0 });
} catch (error) {
if (error instanceof QiblaValidationError) {
console.log("Invalid coordinates:", error.message);
}
}Edge Case Handling
Robust handling of extreme coordinates:
// Polar regions
const arctic = { latitude: 89.5, longitude: 0 };
const result1 = getQiblaDirection(arctic);
// Antimeridian crossing
const pacific = { latitude: 0, longitude: 179.9 };
const result2 = getQiblaDirection(pacific);
// Near Kaaba detection
const nearKaaba = { latitude: 21.422, longitude: 39.826 };
const isNear = isAtKaaba(nearKaaba, 0.01); // Custom tolerance๐งช Accuracy & Validation
This library has been validated against multiple reference implementations:
Reference Implementations
- Perfect accuracy (0.00ยฐ difference) with qibla-direction-typescript
- Excellent accuracy (ยฑ0.5ยฐ max difference) with qibla-main
- Consistent results across edge cases and extreme coordinates
Test Coverage
- โ Distance calculations using Haversine formula
- โ Bearing calculations using great circle formulas
- โ Cardinal direction mapping
- โ Basic magnetic declination approximation
- โ Edge case handling (poles, antimeridian)
Mathematical Foundation
- Great circle bearing calculations for accuracy
- Haversine formula for distance calculations
- Basic magnetic declination approximation for compass corrections
- Proper coordinate validation and normalization
๐ง Library Features
- Zero dependencies: Self-contained for reliability
- Tree-shakeable: Import only the functions you need
- TypeScript native: Built with TypeScript from the ground up
๐ Use Cases
Mobile Applications
// Get user location and calculate qibla
navigator.geolocation.getCurrentPosition((position) => {
const qibla = getQiblaDirection({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
});
displayQiblaDirection(qibla.bearing, qibla.cardinalDirection);
});Prayer Time Applications
import { getQiblaDirection } from "@masaajid/qibla";
import { calculatePrayerTimes } from "@masaajid/prayer-times";
const location = { latitude: 40.7589, longitude: -73.9851 };
// Calculate prayer times
const prayerTimes = calculatePrayerTimes({
method: "ISNA",
location: [location.latitude, location.longitude],
});
// Calculate qibla direction
const qibla = getQiblaDirection(location, {
includeCardinalDirection: true,
});
console.log("Prayer Times:", prayerTimes);
console.log("Qibla Direction:", qibla);Compass Applications
const result = calculateQiblaWithCompass(location, {
includeMagneticDeclination: true,
includeCardinalDirection: true,
});
// Display compass information
console.log(
`Point your compass ${result.magneticBearing}ยฐ (${result.cardinalDirection})`
);
console.log(`Magnetic declination: ${result.magneticDeclination}ยฐ`);๐๏ธ Development
Building
# Install dependencies
bun install
# Type checking
bun run typecheck
# Run tests
bun test
# Build for distribution
bun run build
# Development mode
bun run devTesting
# Run all tests
bun test
# Watch mode
bun test --watch
# Coverage report
bun test --coverage๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
Mathematical Foundation
- Great Circle Calculations - Standard geodetic formulas for accurate bearing calculations
- Haversine Formula - Distance calculations on spherical surfaces
- Basic Magnetic Declination - Simplified magnetic declination approximation for compass corrections
Validation References
- qibla-direction-typescript - Perfect accuracy validation (0.00ยฐ difference)
- qibla-main - Cross-reference validation for algorithm verification
- Multiple coordinate systems - Ensuring global accuracy and edge case handling
Related Projects
- @masaajid/prayer-times - Comprehensive Islamic prayer times calculation library
- Masaajid Platform - Community masjid discovery and management platform
Part of the Masaajid Platform ecosystem - Building comprehensive Islamic software tools for the global Muslim community.