How to Install and Use the Cordova Background Plugin for Route Tracking

Every Appery.io app comes with the Apache Cordova library automatically installed. This means you have access to default Cordova APIs such as Camera, Contacts, Geolocation, and more. Many users also wanted to add 3rd-party Cordova plugins to the app. To make this process very simple, we’ve added a simple wizard. In this tutorial you are going to learn how to upload a Cordova plugin to your app and use it. You will build an app that will track your route and draw it on a map. The app will do this in the background. (This is a popular feature in fitness apps.)

The first step is to download and install the Cordova Background plugin.

  1. Download the Cordova Background plugin.
  2. Upload upload the plugin into Appery.io as described in this document.
  3. Create a new app, call it Route track.
  4. Add the plugin to your app. Go to App settings -> Cordova plugins -> Imported Cordova plugins and enable the BackgroundMode plugin.

    1

    Installing the Background Cordova plugin

The plugin is now available in the app. Next you are going to build the app UI. The UI is very simple, we have only one label and a Google Maps component.

  1. Open the startScreen page
  2. Remove the header and footer components as we don’t need them in the app
  3. Place a label on a page and call it speed_label, and change its text to Current speed is 0 km/h

    label

    Creating the app UI

  4. Place the Google Maps component below the label
  5. Name the component googlemap, change Dimension to 300px, clear Address, uncheck Show marker, uncheck visible for Googlemap marker, and save

    gmap

    Adding a Google Maps component

Since you are going to find the coordinates and draw the route on the map you will use the Geolocation service in your app (read more about the service here)

  1. Go to Create new and choose Service
  2. Select Geolocation(the service name will be set to GeolocationService)
  3. Next you are going to create a new JavaScript file. Go to Create New and choose JavaScript. Call it Helper, paste the following code, and save the app:
    var Helper = {
        map:null,
        coordinates:[],
        getDistance: function (origin, destination, miles) {
            
            var R = 6371; // Radius of the earth in km
            var dLat = Helper.degrees2radians(destination.lat - origin.lat); 
            var dLng = Helper.degrees2radians(destination.lng - origin.lng); 
            var a = 
                Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(Helper.degrees2radians(origin.lat)) * Math.cos(Helper.degrees2radians(destination.lat)) * 
                Math.sin(dLng/2) * Math.sin(dLng/2)
            ; 
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
            var distance = R * c; // Distance in km
            
            
            var result = (miles) ? distance * 0.621371192 : distance; // convert km to miles
            
            return result;
        },
        
        degrees2radians: function (deg) {
          return deg * (Math.PI / 180);
        },
        initMap:function(){
            Helper.map = Apperyio("googlemap").gmap;
            if (!Helper.map){
                Helper.setInitDelay();
            } else {
                $(".startScreen_googlemap").height(Apperyio("mobilecontainer").height() - 35);
            	geolocation.execute();
                Helper.drowDirections();
            }
        },
        setInitDelay: function()	{
    		setTimeout(Helper.initMap, 50);
    	},
        drowDirections:function(){
            var path = new google.maps.Polyline({
                path: Helper.coordinates,
                geodesic: true,
                strokeColor: '#0000FF',
                strokeOpacity: 1.0,
                strokeWeight: 2
            });
            
            path.setMap(Helper.map);
          
        }
    };

    This code finds your current coordinates and draws them on the map.

  4. Go back to the StartScreen and switch to Data tab
  5. Choose Device as the datasource and GeolocationService from the menu and expand the menu for geolocation

    5

    Adding the Geolocation service to the page

  6. Delete the mapping for the Success event and open the Events tab. Selectgeolocation for Components, Success for Common events, and Run JavaScript for Action.
  7. Put in the following JavaScript code:
    var newPoint = {lat:data.coords.latitude, lng:data.coords.longitude, time: (new Date().getTime())};
    var previousPoint = Helper.coordinates[Helper.coordinates.length - 1];
    
    if (Helper.coordinates.length){
        var distanceDelta = Helper.getDistance(previousPoint, newPoint);
        
        var rounded = Math.round((distanceDelta * 60) * 100) / 100;
        Apperyio("speed_label").text("Current speed is "+rounded + " km/h");
    }
    
    Helper.coordinates.push(newPoint);
    
    Helper.drowDirections();
    
    Helper.map.setCenter(newPoint);
    

    This code calculates your speed, writes it in the label, and interacts with our major code Helper giving current data to it.

  8. Click Save

    7

    Running JavaScript after the service is invoked

  9. Go back to Design tab of the page

You are almost done, now you need to add the code be be invoked when the app launches.

  1. Open the Events tab, and choose Device ready event and Run JavaScript as Action for the component startScreen page. Paste the following code:
    // Android customization
    cordova.plugins.backgroundMode.setDefaults({ text:'Doing heavy tasks.'});
    // Enable background mode
    cordova.plugins.backgroundMode.enable();
    
    // Called when background mode has been activated
    cordova.plugins.backgroundMode.onactivate = function () {
    setTimeout(function () {
    // Modify the currently displayed notification
    cordova.plugins.backgroundMode.configure({
    text:'Running in background for more than 5s now.'
    });
    }, 5000);
    };

    You are calling the background plugin in this code. It is called with a timeout of 5 seconds. As you are planning to use it for outdoor exercise, you also use it to display how long the app has been running.

  2. Save and create one more Run JavaScript event, this time for the Start Screen component and the Page Show event. Paste this code
    Helper.initMap();
    

    This code is needed for your main JavaScript helper.

  3. Save and add this last code to call the geoservice – startScreen as Component, Load as Event, Run JavaScreept as Action
    setInterval(function(){
    geolocation.execute();
    },10000);
    

The app is finished and ready for testing.

As this app uses a custom Cordova plugin, you need to build a binary and install on the device to test the app on the actual device. Appery.io makes it easy to export a binary.

123

Testing on a device