Background Location

Enable High Accuracy Geolocation Tracking in your App

The Despia Background Location SDK enables your application to track user location in the background, even when your app is not actively in use. This provides seamless location tracking capabilities while optimizing for battery life and accuracy.

Quick Start

1. Enable Native Background Tracking

First, you need to enable background location tracking on the user's device:

window.despia = "backgroundlocationon://"

2. Start Watching Location

After enabling background tracking, start watching the user's location:

if ("geolocation" in navigator) {
    const watchId = navigator.geolocation.watchPosition(
        position => console.log(position),
        error => console.error("Error:", error.message),
        { enableHighAccuracy: true }
    )
}

3. Stop Tracking

When you want to stop tracking location, disable background tracking and clear the watch:

window.despia = "backgroundlocationoff://"
navigator.geolocation.clearWatch(watchId)

How It Works

Background Tracking:

  • The SDK enables native background location tracking on the device

  • Location updates continue even when the app is minimized

  • Battery optimizations are automatically applied

Location Watching:

  • Standard Web Geolocation API is used to receive location updates

  • Position data includes coordinates, accuracy, heading, and speed

  • Error handling provides feedback on any issues that occur

Data Handling:

  • Location data is delivered through the watchPosition callback

  • Updates can be processed for your app's specific needs

  • Options allow for customizing accuracy, timeout, and maximumAge

Location Configuration Options

You can customize tracking behavior with these options:

const options = {
    enableHighAccuracy: true,  // Use GPS for better accuracy (uses more battery)
    timeout: 5000,             // How long to wait for a reading (milliseconds)
    maximumAge: 0              // Accept cached positions up to this age (milliseconds)
}

Implementation Examples

Below is a comprehensive implementation example that works across different platforms and frameworks. The code demonstrates how to enable background tracking, watch for location updates, and process the received data. This can be adapted for various environments including JavaScript frameworks and no-code/low-code platforms.

// 1. Enable background tracking
window.despia = "backgroundlocationon://"

// 2. Start tracking
if ("geolocation" in navigator) {
    const watchId = navigator.geolocation.watchPosition(
        (position) => {
            console.log(position); // Process location data if using regular JavaScript
            
            // EXAMPLES FOR NO-CODE/LOW-CODE TOOLS
            
            // ---------- WEWEB ----------
            // WEWEB example using wwWorkflow to handle location data
            
            // 1. Create a Native WeWeb Global Workflow to receive location data
            // 2. Add Logic to that Workflow to process the location as needed
            // 3. Call your Workflow from exactly this line of code here:
            wwLib.wwWorkflow.executeGlobal('YOUR WEWEB WORKFLOW ID', {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                accuracy: position.coords.accuracy,
                timestamp: position.timestamp
            });
            
            // ---------- WIZED ---------- 
            // WIZED example using Wized's JS API
            v.locationData = {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                accuracy: position.coords.accuracy,
                timestamp: position.timestamp
            };
           
            // Create a request (API Call) that will send location to your server
            const result = await Wized.requests.execute('REQUEST NAME TO PROCESS LOCATION');
            console.log(result); // Or set result as variable if needed
            
            // ---------- NORDCRAFT / TODDLE ---------- 
            // For Nordcraft / Toddle - simply install the "Despia" Package and listen for the event callback.
            // Clone the package from here: https://toddle.dev/projects/despia_package/branches/main
            // Or run following after registering an "onLocation" Event in your Custom Action:
            ctx.triggerActionEvent("onLocation", {
                latitude: position.coords.latitude,
                longitude: position.coords.longitude,
                accuracy: position.coords.accuracy,
                timestamp: position.timestamp
            });
        },
        (error) => {
            console.error("Error:", error.message);
        },
        { enableHighAccuracy: true }
    );
}

Make sure to call backgroundlocationon:// before running the web-based Geolocation API. This ensures that location data is served through the device's native functionality, providing better accuracy and improved performance. Using this method also allows you to reuse your web app code seamlessly within your native app.

Location Data Structure

The location data is provided as a position object with standardized fields:

{
  "timestamp": 1745861487040,  // Timestamp in milliseconds since Unix epoch
  "coords": {
    "latitude": 33.66366814600508,     // Latitude in decimal degrees
    "longitude": -117.82504144897301,  // Longitude in decimal degrees
    "altitude": 26.780719757080078,    // Altitude in meters above sea level (if available)
    "accuracy": 3.529386594010958,     // Accuracy of lat/long in meters
    "altitudeAccuracy": 3,             // Accuracy of altitude in meters (if available)
    "heading": 243.5,                  // Direction of travel in degrees (0-359.9, where 0 is north)
    "speed": 4.8                       // Speed in meters per second (about 10.7 mph)
  },
  "watchID": 513  // ID of the watch operation (implementation detail)
}

Best Practices

Battery Optimization

  • Use enableHighAccuracy: true only when precise location is required

  • Implement dynamic tracking intervals based on movement and app state

  • Stop tracking when not needed with backgroundlocationoff://

Error Handling

  • Implement proper error handling for timeout scenarios

  • Handle cases where location might be unavailable

  • Log errors appropriately for debugging

Performance

  • Store watchId for proper cleanup

  • Consider caching location data when appropriate

  • Use the timeout parameter appropriately based on your app's needs

Complete Implementation Example

Here's a complete implementation that includes starting and stopping location tracking with error handling:

// Enable background tracking
window.despia = "backgroundlocationon://";

// Setup location tracking with error handling
function startLocationTracking() {
    let watchId;
    
    try {
        if ("geolocation" in navigator) {
            watchId = navigator.geolocation.watchPosition(
                (position) => {
                    // Process location data
                    processLocation(position);
                },
                (error) => {
                    handleLocationError(error);
                },
                {
                    enableHighAccuracy: true,
                    timeout: 10000,
                    maximumAge: 5000
                }
            );
        } else {
            console.error("Geolocation is not supported by this browser");
        }
    } catch (error) {
        console.error("Error starting location tracking:", error);
    }
    
    return watchId;
}

function stopLocationTracking(watchId) {
    if (watchId) {
        window.despia = "backgroundlocationoff://";
        navigator.geolocation.clearWatch(watchId);
        console.log("Location tracking stopped");
    }
}

function processLocation(position) {
    // Implement your location processing logic here
    console.log("Location updated:", position);
}

function handleLocationError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            console.error("User denied the request for location access");
            break;
        case error.POSITION_UNAVAILABLE:
            console.error("Location information is unavailable");
            break;
        case error.TIMEOUT:
            console.error("The request to get user location timed out");
            break;
        default:
            console.error("An unknown error occurred:", error.message);
    }
}

// Start tracking
const locationWatchId = startLocationTracking();

// Later, when done tracking:
// stopLocationTracking(locationWatchId);

Troubleshooting

Common Issues

Permission Denied

  • Verify that your app has the proper permission declarations

  • Check if the user has previously denied permissions

  • Implement a retry strategy with user guidance

Location Unavailable

  • Check if device has location services enabled

  • Verify that the device has a GPS or network connection

  • Consider fallback options for location determination

Tracking Stops in Background

  • Ensure background location is properly enabled with backgroundlocationon://

  • Verify that the device allows background location services

  • Check battery optimization settings that might affect background operation

Need Help?

For additional support or questions, please contact our support team at support@despia.com

Updated on