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

Instant PhoneGap

January 2014


Begin your journey of building amazing mobile applications using PhoneGap with the geolocation API.

(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:

Books to Consider

comments powered by Disqus