Background Location SDK
Track your user's current location and monitor location changes, even when the app runs in the background, using a hybrid solution.
Written By despia
Last updated About 1 year ago
SDK Usage
// 1. Enable native background tracking
window.despia = "backgroundlocationon://"
// 2. Start watching location with navigator
if ("geolocation" in navigator) {
const watchId = navigator.geolocation.watchPosition(
position => console.log('onLocation', position),
error => console.error("Error:", error.message),
{ enableHighAccuracy: true }
)
}
// Stop tracking
window.despia = "backgroundlocationoff://"
navigator.geolocation.clearWatch(watchId)
Location Options
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
ExamplesStart Tracking
if ("geolocation" in navigator) {
// Enable background tracking
window.despia = "backgroundlocationon://"
const watchId = navigator.geolocation.watchPosition(
(position) => {
console.log('onLocation', position)
},
(error) => {
console.error("Error:", error.message)
},
options
)
}
Stop Tracking
function stopTracking() {
window.despia = "backgroundlocationoff://"
navigator.geolocation.clearWatch(watchId)
}
Custom Configuration
// Define custom tracking options
const customOptions = {
enableHighAccuracy: true, // Use GPS
timeout: 10000, // 10 second timeout
maximumAge: 5000 // Accept readings up to 5s old
}
// Start tracking with custom options
if ("geolocation" in navigator) {
window.despia = "backgroundlocationon://"
const watchId = navigator.geolocation.watchPosition(
position => console.log('Location:', position),
error => console.error('Error:', error),
customOptions
)
}
Error Handling
function handleLocationError(error) {
console.error("Location error:", error.message)
// Handle specific error cases
}
Tips
Request permissions before tracking
Handle background state changes
Consider battery impact
Monitor accuracy levels
Clean up watchers when done
Need help? Email us at support@despia.com