geolocation-native
v0.1.0
Published
Native geolocation API for Node.js and Electron, providing browser-compatible navigator.geolocation interface
Maintainers
Readme
geolocation-native
Native geolocation API for Node.js and Electron, providing browser-compatible navigator.geolocation interface using native system bindings.
✨ Features
- 🌍 Browser-compatible API - Exact same interface as
navigator.geolocation - 🖥️ Cross-platform support - Windows, macOS, and Linux with full native integration
- ⚡ Zero build requirements - Prebuilt binaries for all platforms
- 🔒 Complete permission management - Request, query, and navigate to settings
- 📱 Electron-ready - Perfect for desktop applications
- 🚀 Production-ready - Used in enterprise applications
🚀 Installation
npm install geolocation-nativeThat's it! No build tools required - prebuilt binaries are automatically downloaded for your platform.
System Requirements
- Node.js: 18.0.0+ (supports 18, 20, 22)
- Electron: 25.0.0+ (supports 25, 27, 28)
- Platforms: Windows, macOS, Linux (x64, ARM64)
Usage
Basic Usage (Node.js)
const { geolocation } = require('geolocation-native');
// Get current position
geolocation.getCurrentPosition(
(position) => {
console.log(`Lat: ${position.coords.latitude}`);
console.log(`Lng: ${position.coords.longitude}`);
console.log(`Accuracy: ${position.coords.accuracy}m`);
},
(error) => {
console.error(`Error ${error.code}: ${error.message}`);
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 60000
}
);
// Watch position changes
const watchId = geolocation.watchPosition(
(position) => {
console.log('Position update:', position.coords);
},
(error) => {
console.error('Watch error:', error);
}
);
// Stop watching
geolocation.clearWatch(watchId);Permission Management
// Check current permission status
const permission = geolocation.queryPermission();
console.log(permission); // 'granted', 'denied', or 'prompt'
// Request permission (shows system dialog)
const granted = await geolocation.requestPermission();
if (granted) {
// Permission granted, can access location
}
// Open system location settings
await geolocation.openLocationSettings();
// Open app-specific permission settings (Windows)
await geolocation.openAppPermissionSettings();
// Browser-style permissions API
const permissionStatus = await geolocation.permissions();
console.log(permissionStatus.state); // 'granted', 'denied', 'prompt'Electron Integration
Main Process (main.js):
const { ipcMain } = require('electron');
const { geolocation } = require('geolocation-native');
// Handle geolocation requests from renderer
ipcMain.handle('geolocation:getCurrentPosition', async (event, options) => {
return new Promise((resolve, reject) => {
geolocation.getCurrentPosition(resolve, reject, options);
});
});Preload Script (preload.js):
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('geolocation', {
getCurrentPosition: (options) => ipcRenderer.invoke('geolocation:getCurrentPosition', options),
// ... other methods
});Renderer Process (standard web API):
window.geolocation.getCurrentPosition(
(position) => console.log(position),
(error) => console.error(error)
);See examples/electron/ for complete integration example.
API Reference
Methods
getCurrentPosition(successCallback, errorCallback?, options?)
Get the current position of the device.
successCallback: Function called withPositionobject on successerrorCallback: Function called withPositionErrorobject on erroroptions: Configuration object (optional)
watchPosition(successCallback, errorCallback?, options?)
Watch the position of the device for changes.
- Returns:
number- Watch ID for use withclearWatch()
clearWatch(watchId)
Stop watching position changes.
watchId: Watch ID returned bywatchPosition()
Permission Management Methods
queryPermission() → string
Check current permission status without prompting user.
- Returns:
'granted','denied', or'prompt'
requestPermission() → Promise<boolean>
Request location permission from user (shows system dialog).
- Returns:
Promisethat resolves totrueif granted
openLocationSettings() → Promise<boolean>
Open system location settings page.
- Returns:
Promisethat resolves totrueif settings opened
openAppPermissionSettings() → Promise<boolean>
Open app-specific location permission settings.
- Windows: Opens app permissions page
- macOS/Linux: Falls back to general location settings
- Returns:
Promisethat resolves totrueif settings opened
permissions() → Promise<PermissionStatus>
Browser-style permissions API.
- Returns:
Promise<{state: string, onchange: null}>
Options
{
enableHighAccuracy: false, // Request high accuracy location
timeout: Infinity, // Timeout in milliseconds
maximumAge: 0 // Maximum age of cached position
}Position Object
{
coords: {
latitude: number, // Latitude in decimal degrees
longitude: number, // Longitude in decimal degrees
altitude: number | null, // Altitude in meters
accuracy: number, // Accuracy in meters
altitudeAccuracy: number | null,
heading: number | null, // Heading in degrees (0-360)
speed: number | null // Speed in meters per second
},
timestamp: number // Timestamp in milliseconds
}PositionError Object
{
code: number, // Error code (1, 2, or 3)
message: string, // Error description
PERMISSION_DENIED: 1,
POSITION_UNAVAILABLE: 2,
TIMEOUT: 3
}Development
Building from Source
# Install dependencies
npm install
# Configure native build
npm run configure
# Build the project
npm run build
# Or rebuild everything
npm run rebuildRunning Tests
# Run all tests
npm test
# Run tests in watch mode
npm run test:watchExamples
See the examples/ directory for complete usage examples:
examples/nodejs/basic.js- Basic Node.js usage with location acquisitionexamples/nodejs/permissions.js- Permission management demonstrationexamples/electron/- Complete Electron application with UIexamples/linux/test.js- Linux-specific GeoClue2 integration testexamples/macos/test.js- macOS Core Location integration test
Run Node.js examples:
node examples/nodejs/basic.js
node examples/nodejs/permissions.jsRun Electron example:
cd examples/electron
npx electron .Run platform-specific tests:
# Linux (or WSL)
node examples/linux/test.js
# macOS
node examples/macos/test.js🏗️ Platform Support
Windows ✅ Complete
- Native Integration: Windows Location API (WinRT) with full async support
- Permissions: Native permission dialogs and settings navigation
- Features: All APIs supported including app-specific settings
- Requirements: Windows 10+ with location services enabled
- Accuracy: GPS, WiFi, cellular, and network-based location
macOS ✅ Complete
- Native Integration: Core Location framework with CLLocationManager
- Permissions: macOS privacy system integration with automatic prompts
- Features: Full API support including System Preferences navigation
- Requirements: macOS 10.15+ with location services enabled
- Accuracy: GPS, WiFi, cellular, and Bluetooth location sources
Linux ✅ Complete
- Native Integration: GeoClue2 D-Bus service with system-level permissions
- Permissions: Desktop environment integration (GNOME/KDE settings)
- Features: All APIs supported with desktop environment settings
- Requirements: GeoClue2 service, systemd-based distributions
- Accuracy: NetworkManager-based location (WiFi, cellular, IP-based)
📦 Binary Distribution
This package uses prebuilt binaries for fast, zero-config installation:
- ✅ No build tools required for most users
- ✅ Automatic platform detection and binary download
- ✅ Fallback to source build if binary unavailable
- ✅ Multi-architecture support: x64, ARM64
- ✅ CI/CD integration with automated binary building
For more details, see Binary Distribution Guide.
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see the LICENSE file for details.
Acknowledgments
- Inspired by the W3C Geolocation API specification
- Built with Node-API for maximum compatibility
- Cross-platform native code patterns from various open-source projects
