Skip to content

Instantly share code, notes, and snippets.

@grantges
Last active December 12, 2015 07:48
Show Gist options
  • Save grantges/4739081 to your computer and use it in GitHub Desktop.
Save grantges/4739081 to your computer and use it in GitHub Desktop.
Quick code snippets to easily set up a background task to poll geolocation information on iOS on a 10 second interval
// Setup Geoloaction Background Tasks for the app
Ti.Geolocation.purpose = "This app would like to use your location.";
Ti.App.iOS.registerBackgroundService({url: "geoBackgroundTask.js"});
/**
* Note: If you are programming in a standard project for Titanium,
* this snippet would probably go in your app.js file
* /
/**
* Setting up Geolocation to run as a background Task in IOS
*
* Include the underscore library - you need to do this since background tasks run outside of the scope
* of the main application. Its found under the alloy folder for alloy based projects, otherwise you can
* find it here:
*
* http://underscorejs.org/
*/
Ti.include("alloy/underscore.js");
function getCurrentPosition() {
// Setup a variable to store the locally stored list.
var waypoints = Ti.App.Properties.getList("waypoints");
//Call the Geolocation API to get current position (passes a callback function)
Ti.Geolocation.getCurrentPosition(function(e){
// Create a marker object for the lat/long and timestamp
var waypoint = {
timestamp: new Date(),
latitude: e.coords.latitude,
longitude: e.coords.longitude,
};
//Just in case this is the list hasn't been initialized with data, make sure we create an array
if(!_.isArray(waypoints)){
waypoints = [];
}
// Add the way point to the list
waypoints.push(waypoint);
// Update the persistent List
Ti.App.Properties.setList("waypoints", waypoints );
Ti.API.info("GEOMARKERS: "+ JSON.stringify(waypoints));
//Cleanup
waypoints = null;
});
}
/**
* Setup Interval check for background service. Current Position should be recorded, and added to an
* locally stored list.
*/
setInterval(getCurrentPosition, 10000);
<!--
Add this snippet within the <ti:app> tags of your tiapp.xml file
-->
<backgroundModes>
<mode>location</mode>
</backgroundModes>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment