Easy Code Share > Cordova > Cordova APP Calculate Geo Map Distance on Walking

Cordova APP Calculate Geo Map Distance on Walking

Using Cordova Plugins, you can calculate Geo map distance of the route you have walked. The Plugin used to get latitude and longitude for map distance is Cordova Geolocation, which read GPS chip to report coordinates. In addition, markers for distance tracking points on Google Maps provide visual impression of how far you have walked.

How do you use it? Press start button, walk a distance around several meters, and temporarily switch to pause. Then you can see the path you had roamed on in meters. Also you can resume measuring your movement. On Google Maps tab, a complete route shows for you.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 6 minutes



Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.


Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.


The Basics

Topics discussed in the section are distance calculation for latitude and longitude, retrieval of mobile GPS locations, Cordova default database, and Google Maps. Some of topics make references to our other posts in details.


Calculate Geo Map Distance

Based on a popular algorithm for latitude and longitude map distance, we try to accumulate all line segments of a route to become a traveling distance. It is mathematically complex to realize the theory behind algorithm, but you can still implement the calculation by directly leveraging JavaScript Math functions.

function geoDistance(lat1, lon1, lat2, lon2) {
    const R = 6371e3; // metres
    const phee1 = lat1 * Math.PI/180; // φ, λ in radians
    const phee2 = lat2 * Math.PI/180;
    const delta_phee = (lat2-lat1) * Math.PI/180;
    const delta_lambda = (lon2-lon1) * Math.PI/180;
    const a = Math.sin(delta_phee/2) * Math.sin(delta_phee/2) +
              Math.cos(phee1) * Math.cos(phee2) *
              Math.sin(delta_lambda/2) * Math.sin(delta_lambda/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    const d = R * c; // in metres
    return d;


GPS Coordinates of Mobile Phones

Cordova Geolocation Plugin is available to get coordinates from GPS chip in mobile phones, and store them in a Cordova default database WebSQL used in our example. We make latitude and longitude of traveling coordinates to express a walking route in Google Maps for visual purpose.

More complicatedly, we had written an article about tracking GPS positions of family and friends integrating more topics inside. You can refer it to be an advanced tutorials.


Geo Map Distance

Before you build this example as an APP, let’s see the process from location dots to line segments, and then display information on Google Maps to indicate how far people walked.


Latitude & Longitude

Cordova APPs retrieve latitude and longitude using Geolocation Plugin. When device is ready, the Plugin provides an object navigator.geolocation with methods for getting coordinates. The following function getCoordinates() performs a routine job per 60 seconds, unless the walker toggle a selection to pause the job.

function getCoordinates() {
    navigator.geolocation.getCurrentPosition(onSuccess, onError);
    if(!select_pause) setTimeout(getCoordinates, 60000); // milliseconds
function onSuccess(pos) {
    // Update global variables
    prevLat = (latitude > 0) ? latitude : pos.coords.latitude;
    prevLon = (longitude > 0) ? longitude : pos.coords.longitude;;
    latitude = pos.coords.latitude;
    longitude = pos.coords.longitude;
    if(press_start) {
        the_distance = 0;
        press_start = false;
    } else {
        the_distance += geoDistance(prevLat, prevLon, latitude, longitude);
    // insert
    sql="INSERT INTO route (timestamp, lat, lon, distance) VALUES (?, ?, ?, ?)";
    dbInst.execute(sql, [ getTimeStamp(), pos.coords.latitude, pos.coords.longitude, the_distance ], refreshAll);
    console.log('Latitude: '+ pos.coords.latitude + ' ' +
                'Longitude: '+ pos.coords.longitude);

There is a callback function onSuccess() in this routine job, each time a pair of new latitude and longitude arrives, the value of a global variable the_distance increases. At the same time, a new traveling node is inserted into database with coordinates and a timestamp. Pressing RESTART button will reset the Geo map distance, and calculate a new trip.

Reset Route and Start Tracking

Let’s talk about the database where tracking points are stored. We use a WebSQL database class, which has been mentioned before, to leverage the benefit of reducing coding efforts. As shown in the script, when a database instance is produced with a database name route_db, its callback function will create a table route if not existed.

var dbInst;
$(document).ready(function() {
    dbInst = new dbClass("route_db", "Route DB", InitDB);
/* WEBSQL */
function InitDB() {
    sql="CREATE TABLE IF NOT EXISTS route (timestamp INTEGER, lat REAL, lon REAL, distance REAL)";


The Callback Sequence

Under calling to asynchronous APIs, there would be a sequence of callback functions used to refresh states in screen layout. These callback functions as below subsequently illustrate increasing history of Geo distance on map.

  1. onSuccess() : gain latitude and longitude (in the above).
  2. refreshAll() : find traveling nodes so far.
  3. refreshData() : list nodes, and draw growing distance on Geo map.
function refreshAll() {
    sql="SELECT * FROM route";
    dbInst.execute(sql, [], refreshData);
function refreshData(rows, n, rowsAffected) {
    html = "";
    for(var i=0; i<n; i++) {
        console.log(rows[i].timestamp + " / " + rows[i].lat + " / " + rows[i].lon + " / " + rows[i].distance );
        html += "<tr><td width='50%'>"+convertTimeStamp(rows[i].timestamp)+"</td>";
        html += "<td width='20%'>"+rows[i].distance.toFixed(2)+"</td></tr>";
    // List traveling nodes

For example, at 12:41, a new walker resets the distance. In about 10 minutes, he has walked about 1,191 meters. At that time, he pressed PAUSE to stop increasing.

Pause to See Geo Map Distance


GPS Distance on Google Maps

Let’s display visual locations on map now. The coordinates from GPS chips presented on Google Maps make Geo distance more clear. When device is ready, the jQuery $.getScript() request Google for a new map. A callback function gMapCallback() anchors current position in center with a proper zooming factor.

/* Google Maps */
function gMap() {
function gMapCallback() {
    center = new google.maps.LatLng(latitude, longitude);
    config = {center: center, zoom: 10,};
    theMap = new google.maps.Map(document.getElementById("googleMap"), config);
    console.log( "Map Created" );

Each time a new node is created, Google Maps draw it on the corresponding location with a marker. We choose a small white square my-dot.png as the marker in the example.

function refreshData(rows, n, rowsAffected) {
    // Add a marker on Google Maps
    center = new google.maps.LatLng(rows[n-1].lat, rows[n-1].lon);
    marker = new google.maps.Marker({
        position: center, icon: "img/my-dot.png",

As the walking route below, several white square dots from left to right constitute a walking path. But the path seems broken in the middle. It could be resulted from some incorrect GPS data in the middle of trip. However, for long-team view, the eventual dot on the right-most place can really locate a far distance from the beginning dot. Summation of all distance segments is about 1,191 meters. The way would measure exercise intensity of the walker in ease.

Google Maps Show The Walking Route

In the picture above, white square dots surround a company called ASML Taiwan ACE, thus segments connecting successive dots present the walker’s route.


Build a Cordova APP

Most developers use Cordova CLI command lines to build APPs. You have to determine at least three arguments for the Cordova project before starting to build.

  • PATH: distance
  • ID: com.easycodeshare.geodistance
  • NAME(human readable): GeoDistance
c:\>cordova create distance com.easycodeshare.geodistance GeoDistance
c:\>cd distance
c:\distance>cordova platform add android
c:\distance>cordova plugin add cordova-plugin-geolocation

Once the project is created, replace content of the folder distance/www with all downloaded source codes. Subsequently, add the Platform Android and the Plugin Geolocation using the command lines as above.

Don’t use CDN in Cordova projects, so you should download jQuery and jQuery Mobile files as the following placement.

<link rel="stylesheet" href="css/1.4.5/jquery.mobile.min.css">
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/1.4.5/jquery.mobile.min.js"></script>

Finally, let’s build an Cordova APP using one command line.

c:\distance>cordova build android
Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=undefined (recommended setting)
Using Android SDK: C:\Users\user\AppData\Local\Android\sdk
Subproject Path: CordovaLib
Subproject Path: app
Starting a Gradle Daemon (subsequent builds will be faster)
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.5/userguide/command_line_interface.html#sec:command_line_warnings
40 actionable tasks: 40 up-to-date
Built the following apk(s):



If you are Cordova developers, build this APP not only for studying, but also for fun. Because it really can measure exercise trips for people in common life. Don’t hesitate to ask us for any questions, especially in building process.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!


Learning Tips

Let us suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.

In Google Chrome, there are two ways to inspect a web page using the browser built-in Chrome DevTools:

  • Right-click an element on the page or in a blank area, then select Inspect.
  • Go to the Chrome menu, then select More Tools > Developer Tools.


Suggested Reading

Leave a Comment