Geolocation – using PhoneGap features to improve an app's functionality, write once use everywhere

Exclusive offer: get 50% off this eBook here
Instant PhoneGap [Instant]

Instant PhoneGap [Instant] — Save 50%

Begin your journey of building amazing mobile applications using PhoneGap with the geolocation API with this book and ebook

$12.99    $6.50
by Gustavo De La Vega Alvarez | December 2013 | Open Source

This article by Gustavo De La Vega Alvarez, the author of Instant PhoneGap, has discussed how to implement geolocation in our app, we will use the API that PhoneGap provides us as part of a bunch of methods to use through our app. To build this, we need to create a JS file called myplaces.js. Create the file once using a text editor program such as Sublime Text or Notepad. Then we will perform the following steps:

(For more resources related to this topic, see here.)

Step 1 – define global variables

We include the following variables and functions in our file:

var map; var latitud; var longitud; var xmlDoc = loadXml("puntos.xml"); var marker; var markersArray = []; function loadXml(xmlUrl) { var xmlhttp; if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }"GET", xmlUrl, false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; return xmlDoc; }

With this code, we build our first function called loadXmlthat just loads the information into the XML file and then in to the smart phone memory.

Step 2 – get current position

We will build the following functions that we need to show our current position in Google Maps:

  • getCurrentPosition: This function receives an object with the latitude and longitude. These values are set to two variables defined as global variables with the same name. This function receives three parameters, which are as follows:
    • A function to manage the current latitude and longitude
    • A function to manage errors if they occur when the device is trying to get the position
    • Options to configure
  • maximumAge: This is the time required to keep our position on the cache in milliseconds
  • timeout: This is the maximum time required to wait for an answer from the getCurrentPosition function in milliseconds
  • enableHighAccuracy: This provides a more accurate location

    The values of these functions can be set to either True or False.

    The following is the code for the preceding functions:

    getCurrentPosition(coordinates, errors, { maximumAge : 3000, timeout : 15000, enableHighAccuracy : true }

    The following is the code for the coordinates and errors functions:

    function coordinates(position) { latitud = position.coords.latitude; /* saving latitude */ longitud = position.coords.longitude; /* saving longitude*/ loadMap(); }// end function function errors(err) { /* Managing errors */ if (err.code == 0) { alert("Oops! Something is wrong"); } if (err.code == 1) { alert("Oops! Please accept share your position with us."); } if (err.code == 2) { alert("Oops! We can't get your current position."); } if (err.code == 3) { alert("Oops! Timeout!"); } }// end errors

  • LocateMe: This function checks whether the device supports the PhoneGap geolocalization API or not. If the device supports the API, then this function calls a method to obtain the current position. If the device doesn't support geolocalization API, then we will use the current position's function, getCurrrentPosition, explained previously. The complete code for the LocateMe function is as follows:

    function locateMe() { if (navigator.geolocation) { /* The browser have geolocalization */ navigator.geolocation.getCurrentPosition(coordinates, errors, { maximumAge : 3000, timeout : 15000, enableHighAccuracy : true }); } else { alert('Oops! Your browser doesn't support geolocalization'); } }

Step 3 – showing the current position using Google Maps

To do this, we use a function that we called loadMap. This function is responsible for loading a map using Google Maps API with the current position. Also, we use a JavaScript object called myOptions with three properties, zoom to define the zoom, center to define where the maps will be centered, and mapTypeId to indicate the map style (that is Satellite).

Following the code, we find two lines: the first one initializes the actualHeight variable according to the value that is returned by the getActualContentHeight function. This function returns the height that the map needs to have according to the screen size. In the second line, we change the height of the div "map canvas" through the jQuery Mobile method's CSS. In the following code file, we set the variable map with the google.maps.Map object that receives the parameters, the HTML element, and the myOptions object. We use an additional event to resize the map when the screen size changes.

Now, we create a new marker object google.maps.Marker with four properties: position for the place of the marker, map that is the global variable, icon to define the image that we want to use as a marker, and the tooltip with the property title.

We have two functions: the first one is createMarkers that allows us to read the XML file with the points uploaded in memory and, after that, puts the markers in the map with our second function addMarker that receives four parameters (the global map variable, point name, address and phone, and the google.maps.LatLng object with the point coordinates) to build the marker. We add a click event to show all the information about the place.

Finally, we use the removePoints function that clears the maps, thereby deleting the points loaded.

This is the code for the JS file:

function loadMap() { var latlon = new google.maps.LatLng(latitud, longitud); var myOptions = { zoom : 17, center : latlon, mapTypeId : google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions); var mapDiv = document.getElementById('map_canvas'); google.maps.event.addDomListener(mapDiv, 'resize', function(){ google.maps.event.trigger(map,'resize'); }); var coorMarker = new google.maps.LatLng(latitud, longitud); marker = new google.maps.Marker({/* Create the marker */ position : coorMarker, map : map, icon : 'images/green-dot.png', title : "Where am I?" }); }

Step 4 – edit the HTML file

To implement the preceding functions, we need to add some code lines in our HTML file. We need to add the script line to include the new JS file, and add a complete JavaScript in the HTML head tag to execute the locateMe function. Now that the device is ready, another PhoneGap function calls watchPosition to update the position when the user is moving.


This article has shown us how to implement Geolocation in our app. It also shows how to use the API provided by PhoneGap to use in our app. The code for pointing out our current location was also discussed.

Resources for Article:

Further resources on this subject:

Instant PhoneGap [Instant] Begin your journey of building amazing mobile applications using PhoneGap with the geolocation API with this book and ebook
Published: January 2014
eBook Price: $12.99
See more
Select your format and quantity:

About the Author :

Gustavo De La Vega Alvarez

Gustavo De La Vega Alvarez's IT history started when he was an eight-year-old kid. His father gave him a personal computer that worked with cassettes and 5 ¼ " diskettes. He played Buck Rogers in the 21st century. Now, we are in the 21st.

He started programming with an Apple II in the third grade and continued with the Logo programming language. Now, he has his own company, called NativApps that develops mobile apps for third parties using cross-platform languages such as HTML5, CSS, and JavaScript, tools such as PhoneGap, and innovative technologies such as augmented reality.

His education was divided between Business Administration and Computer Science at Universidad de los Andes in Bogotá, Colombia. He started to teach Down Syndrome kids in 1999 on topics such as how to use the PC, word processors, and MSN messenger. His first job as an IT engineer was developing hotel-booking software for a company where his aunt had a job, and another billing software for a law firm. In the early 2000s, he was working for General Motors Colmotores and left the job in 2003 to establish his first company, ProActive Consulting. This company started to work with mobile software and ERPs such as PeopleSoft and SAP. In 2009, he decided to start exploring HTML5 and related tools to develop web apps. Finally, in the same year, he was introduced to PhoneGap since that moment, he has been a PhoneGap believer and a passionate cross-platform developer.

Books From Packt

WordPress Mobile Applications with PhoneGap
WordPress Mobile Applications with PhoneGap

PhoneGap 3 Beginner's Guide
PhoneGap 3 Beginner's Guide

Instant PhoneGap Social App Development [Instant]
Instant PhoneGap Social App Development [Instant]

PhoneGap Mobile Application Development Cookbook
PhoneGap Mobile Application Development Cookbook

PhoneGap Beginner's Guide
PhoneGap Beginner's Guide

PhoneGap 2.x Mobile Application Development Hotshot
PhoneGap 2.x Mobile Application Development Hotshot

Adobe Captivate 7 for Mobile Learning
Adobe Captivate 7 for Mobile Learning

Creating Mobile Apps with jQuery Mobile
Creating Mobile Apps with jQuery Mobile

Your rating: None Average: 1.5 (4 votes)

Post new comment

This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software