Click here to Skip to main content
13,861,088 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


104 bookmarked
Posted 8 Oct 2013
Licenced CPOL

A GPS Location Plotting Android Application

, 9 Oct 2013
Rate this:
Please Sign up or sign in to vote.
Develop an Android application that plots user location on a map continuously.

Sample Image


Recently, I was tasked with writing an application that heavily relied on GPS and mapping of custom hardware devices that were built with location-aware components. Even though I have been using Eclipse for these tasks for quite some time, Android Studio's glittering new features and ease of use caught my attention to try it out for the task. During the few weeks I had worked with Android Studio and with Google Maps Android API V2, I learned some lessons that are worth sharing, so that others need not reinvent the wheel and avoid the known pitfalls on their quest.

In this article, we will try to focus on developing an Android application that uses Google Maps Android API V2, using Android Studio IDE. Very recently Google deprecated and as of March 18th, 2013, stopped issuing API keys for Google Maps Android V1 and started recommending V2. A lot of documentation, books and other resources on the web discuss doing things that are centered around V1 and it is daunting for a new comer to sieve through all that and get some useful information on developing applications using API V2. To add to the confusion, there is not very many resources on the web that discusses using Android Studio for such development. Let us hope to fill that gap here.


Google announced on May 16th, 2013, at their Google I/O conference, Android Studio as their Integrated Development Environment, IDE, of choice to develop Android Applications. Android Studio is essentially InettliJ IDEA from JetBrains, but is heavily focused on the development of Android applications. Android Studio uses Gradle for dependency resolution and most of the project management tasks in the IDE. Android Studio is available for download from here.. Android Studio has an automatic software updater that automatically checks for new updates and updates the IDE to the latest version. As of this writing, the newest version was 0.2.11, Build AI-132.855830.

Prior to Android Studio and even after, majority of developers use Eclipse as a fundamental platform for Android application development. Eclipse is an excellent platform that provides a great IDE for software development in Java, C++ and various other languages.

Create an Android application

I am going to assume that the reader is familiar with the structure of an Android Application and the files involved in making an application, in addition to the concepts of Activity, Intent, Activity life cycle and various states of it during its existence, Resource files and Strings etc. There are many books and text available off the web on Android Application development concepts. We are going to focus on a specific application with a specific tool in this article. I have used a Linux machine with Android Studio. The information in this article could be used effectively for a Windows or Mac machine running same version of Android Studio. Let's dive in.

Android Studio creates a skeletal application when you chose New Project from the initial screen, when started. You are presented with a dialog as shown below. Fill in the Name of the application with any meaningful name such as GPSPlotter, in this example. Fill in the package name for your code, such as com.siriusmicrotech.gpsplotter, in this example. This will be the application name that is going to be used for API Key generation that we discuss later in the article. Please note that the Minimum required SDK is selected as AP11, since Google Maps Android API V2 requires SDK greater than AP8 for it to work. Then click next to accept all the defaults through the subsequent screen presented until the project is created by clicking on Finish.

Sample Image - maximum width is 600 pixels

Here is the screen shot of the skeletal project we have created.

Sample Image

Even though there are many files created in this process, luckily, we are going to focus on only the following five files:

  • activity_main.xml
  • strings.xml
  • AndroidManifest.xml
  • build.gradle

Location Providers

Before we start to modify these files, let us discuss some background on why we do what we do in the following sections. Android devices are equipped with GPS hardware. Android provides a very straight forward API to access Location information derived from GPS hardware along with Wi-Fi and Cellular network connection sources that helps provide location information. Since an application should be able to access the current location information of the device, we need to get the users permission for the application to access this service during installation. During debugging, the application is given permission to access these services, without prompting the user to acknowledge. The following section sets up various permissions for the application to access such as accessing internet, since Maps are to be downloaded from Internet, accessing Storage, since Maps need to be cached and for accessing Location providers such as GPS and other forms of location services. Android Maps also needs OpenGL. Here are the lines added to our AndroidManifest.xml file just above the <aplication><aplication> tag.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="" />
    <!-- External storage for caching. -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- My Location -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <!-- Maps API needs OpenGL ES 2.0. -->
        android:required="true" />

Using Google Maps Android API V2 in our Code

Since Google Maps Android API V2 is not included in the Android Development Kit (ADK) and instead it is included in the Google Play Services API, we need to install it separately. Fire up SDK manager and go to the Extras section and check against the Google Play Services and Google Repository and click Install Packages.

Sample Image

Once Google Play Services API is installed, we need to include it in our project. The very nice tutorial at Google's android developer site is written targeting Eclipse as the platform, it suggests including a reference to the Google Services Library by Importing it into the workspace. This will not work with Android Studio since Gradle is used for dependency resolution here. So, we need to edit build.gradle file as follows, by adding a single line in the dependency section of it. Please note, as of this writing, the UI can not be used to add this dependency for Gradle. The only way is to edit the build.gradle file manually. However, one must realize that this is much simpler than the solution discussed at the developer's site.

dependencies {
    // Google Play Services
    compile ''
    // Support Library
    compile ''

Now, to show a map in our application, we need a Fragment in our layout. This is done by replacing the TextView section in the activity_main.xml file with a Fragment section as follows:







And modifying by deriving the MainActivity class from FragmentActivity instead of Activity, as follows:

public class MainActivity extends FragmentActivity 

Now, technically we have everything on the device side of the application. However, the Map has to come from the Cloud. To access the Maps from the cloud, we need a special authentication key called API Key, given to our application by the Google Cloud services, where the Maps are served from. Even though it sounds very complicated, it is very straight forward to obtain this key by following the instructions given here

Please note that for our purposes, we can use our debug certificate to obtain our API Key. A release certificate should be used for generating this key, only if we are going to publish the application. Once this key is obtained, copy this key into the AndroidManifest.xml file as follows, just above <xmp></xmp> tag.



            android:value="Your API Key Here!!" />

Please note, it is much simpler to connect an Android device to the PC and install this application on it and test it than to use the Emulator. However, please remember to enable USB debugging on the device. If your device is running Jelly Bean, by default, Developer Options section of the Settings menu is hidden to protect the user from doing any harm with this feature. Go to System Settings Menu and scroll all the way down to see if you see Developer Options listed. If it is not listed, to bring the Developer Options to view, select About Phone menu and scroll all the way down where you see Build Number. Keep tapping on Build Number several times rapidly until you see that Developer Options are enabled. Go into Developer Options menu and enable USB debugging by clicking on the check mark against it.

Connect your device to the PC with the USB cable and hit run on the Android Studio Menu. If everything went well, you would see a Google map displayed centered somewhere around the continent of Africa! That's not much work, is it.

Displaying and following our location on the Map

Displaying a map of the world is not very exciting unless we are able to trace our location on it somehow. Now, let us start using our location services that our application has already applied for permission in the AndroidManifest.xml file earlier on. The GoogleMap class provides a neat integration many features, including location tracking. So, the sequence of tasks here are to

  • get the object reference for the map we just displayed
  • tie up a location listener to this map that responds to location changed events from the location services
  • focus our location on the map

We can obtain the map object reference by getting the reference to the Fragment that we inserted in the layout file as follows:

myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(

Now, to mark our location on the map, with a blue arrow icon, we enable the feature in our map object as follows. Note, we check for null since the map may not be available before it is rendered completely. -

if(myMap != null)

Since we now have the object reference for the map, we can now start to listen to the location updates from location services. The recommended method for doing this is to setup a location client for the location services within our Main Activity with the following code

myLocationClient = new LocationClient(getApplicationContext(), this, this);
// once we have the reference to the client, connect it
if(myLocationClient != null)

The LocationClient object constructor takes three parameters, the first is the application context and the second is the object that implements Connection callbacks, such as establishment of connection and Disconnection, and the third is the object that implements Connection failure listener. Since we pass the reference to the MainActivity object as the two call back inputs, we have to implement those methods in our MainActivity class. Once we modify our MainActivity class definition line as follows to implement those two interfaces and the LocationListener interface. Android Studio will prompt us to implement the required methods and will automatically populate our class with the methods.

public class ShowMeOnMap extends FragmentActivity
        implements GooglePlayServicesClient.ConnectionCallbacks,

The following are the methods that are populated by Android Studio to implement those three interfaces:

    public void onConnected(Bundle bundle) {

public void onDisconnected() {


public void onLocationChanged(Location location) {


public void onConnectionFailed(ConnectionResult connectionResult) {


As the names suggests, OnConnected is fired when the the service is connected to our LocationClient object. Here is where we have to register our LocationListener to listen for location updates. So, we edit this method body as follows

public void onConnected(Bundle bundle) {
   myLocationClient.requestLocationUpdates( REQUEST, this); 

As you already know, the this in the requestLocationUpdates call is the reference to our MainActivity since we are implementing the LocationListener Interface here. The first parameter is the LocationRequest object that sets options for the location updates such as update frequency, accuracy etc. This is defined as follows:

private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(5000)         // 5 seconds
            .setFastestInterval(16)    // 16ms = 60fps

In this application, we do not do anything for onDisconnected() and onConnectionFailed() methods and we leave them alone.

Once all these are setup, we are now ready to update our location on the map whenever we receive a new location update from the Location service through the onLocationChanged(Location location) method that we registered with the LocationClient. OnLocationChanged is called back with Location parameter that gives as our current location. To move our map to show our current location (or any other location) in the view. The map view is modeled as a camera looking down on a flat plane. The position of the camera (and hence the rendering of the map) is specified by latitude, longitude, zoom, tilt, and bearing of the location to be shown. So, to show a given location on map, we update the camera to that location. The safest way to move camera to our location is to use moveCamera() method in the GoogleMap class with callbacks as follows. The callbacks prevent the situation where the map is not rendered completely and we are attempting to update the camera.

           new CameraPosition.Builder().target(new LatLng(lat, lng))
), new GoogleMap.CancelableCallback() {
    public void onFinish() {
        // Your code here to do something after the Map is rendered

    public void onCancel() {
        // Your code here to do something after the Map rendering is cancelled

In essence, what we have done so far should result in an application that loads a map and shows our position on it with a blue arrow. This icon will track our location on the map as we move around. However, we have neglected some of the details, for the sake of simplicity here. For instance, we have neglected the life cycle events of the MainActivity where is could be Paused and Resumed etc. In the event of another activity displayed over our MainActivity, preventing it from displaying, our MainActivity will be Paused and sent to the background and an onPause()event is generated. When the user gets back to our activity, it will be Resumed and an onResume() event is generated. Location updates are expensive in terms of battery life. So, as a responsible citizen of the Android application habitat, our application should disable location updates when sent to background and not displayed and enable back again when resumed. This is done by overriding onPause() and onResume() methods of the MainActivity. Please refer to the complete application in the source code bundle. 

To use the source code and create an application for your own, please follow these steps: 

  1. Unzip the source in a folder 
  2. Since Creating API key needs an application name, follow what we said in this article, starting with creating new project in Android Studio, with your preferred application name.
  3. Then copy the contents of from the source you unzipped and paste it in your new completely replacing the contents. Then go over to the very first line in the file and change the line "package com.siriusmicrotech.gpsplotter with your package name that you used during your new project creation.
  4. Copy the contents of activity_main.xml file from the source you unzipped and paste it in your new activity_main.xml file replacing the contents entirely.
  5. Copy and paste contents of build.gradle file from unzipped source on to your new buld.gradle file replacing contents entirely.
  6. Do the same for AndroidManifest.xml file. However, here, you have to change the third line from top to replace com.siriusmicrotech.gpsplotter with your package name and under the <activity> tag, change android:name="com.siriusmicrotech.gpsplotter.MainActivity" with your activity name.
  7. Get your API key from Google Could Services
  8. Copy and paste your API key in the AndroidManifest.xml file to replace string that reads "Your API Key Here!"
  9. That's it.

Points of Interest

Things to pay attention to - Get the latest version of Android Studio build. If you decided to use Android Studio, do not research on the internet for solutions, since almost all the text is written for Eclipse. There is a significant change in the way things are done in Google Maps Android API V2 than it was done in V1. Most of the text in elsewhere in internet are written with reference to V1 and that would cripple your progress real bad. The solution is to head over to Google Developer site for API V2 and you will be much better off.  


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Founder Sirius Microtech LLC
United States United States
Raja.D.Singh is one of the Founders of Sirius Microtech LLC, a Los Angeles based technology company dedicated to provide Innovative Engineering services and excellent, standards compliant solutions for problems faced by Small to Medium sized engineering organizations. Sirius specializes in New Product development for Industrial Automation, Robotics, Alternative Energy and Real Time Embedded Systems.

You may also be interested in...


Comments and Discussions

Questionhelp Pin
Member 1374464924-Mar-18 14:12
memberMember 1374464924-Mar-18 14:12 
QuestionFound compilation error Pin
Member 1198798826-Apr-17 21:04
memberMember 1198798826-Apr-17 21:04 
QuestionIm getting an error of Error:(13, 45) error: cannot find symbol class GooglePlayServicesClient andLocationClient Pin
Member 1301359921-Feb-17 14:26
memberMember 1301359921-Feb-17 14:26 
Questionbuild.gradle error Pin
BM Ashok16-Nov-16 2:30
memberBM Ashok16-Nov-16 2:30 
Questiongradle error Pin
Member 1158145916-Dec-15 5:04
memberMember 1158145916-Dec-15 5:04 
QuestionProblems: activity stays blank Pin
Member 116082723-Nov-15 3:02
memberMember 116082723-Nov-15 3:02 
Question?? Pin
Member 1201527827-Sep-15 12:23
memberMember 1201527827-Sep-15 12:23 
QuestionGPS Pin
Member 115879227-Apr-15 7:06
memberMember 115879227-Apr-15 7:06 
QuestionHow to rotate marker ? Pin
Member 110720736-Jan-15 23:31
memberMember 110720736-Jan-15 23:31 
QuestionIs it possible to do this in offline?? Pin
Vijaydhas4-Nov-14 20:41
memberVijaydhas4-Nov-14 20:41 
QuestionGreat Work + Small Question Pin
Justin Weldon8-Oct-14 1:10
memberJustin Weldon8-Oct-14 1:10 
QuestionSymbol 'R' error Pin
Kinrob12-Jul-14 1:49
memberKinrob12-Jul-14 1:49 
AnswerRe: Symbol 'R' error Pin
kusuma chowdary22-Sep-17 1:48
memberkusuma chowdary22-Sep-17 1:48 
Questionhow do i run the proyect? Pin
Member 109145293-Jul-14 10:24
memberMember 109145293-Jul-14 10:24 
QuestionRE: Build gradle error Pin
Tontoy12-Jun-14 19:11
memberTontoy12-Jun-14 19:11 
QuestionThe Download link appears to be broken Pin
Michael B Pliam12-May-14 12:38
memberMichael B Pliam12-May-14 12:38 
QuestionCompatibility with Eclipse Pin
MJR4PJCT29-Jan-14 14:11
memberMJR4PJCT29-Jan-14 14:11 
AnswerRe: Compatibility with Eclipse Pin
Dirk Diggler4-Jun-14 7:24
memberDirk Diggler4-Jun-14 7:24 
QuestionGradle Pin
Malik Sajjad Awan16-Jan-14 1:02
memberMalik Sajjad Awan16-Jan-14 1:02 
GeneralThank you! Pin
Member 104493556-Dec-13 2:53
memberMember 104493556-Dec-13 2:53 
QuestionAbout GPS Plotting Pin
Member 1038549218-Nov-13 18:02
memberMember 1038549218-Nov-13 18:02 
QuestionCould not find Pin
barabek31-Oct-13 12:25
memberbarabek31-Oct-13 12:25 
QuestionErrors & The only way is to edit the build.gradle file manually Pin
Ernst Sauer14-Oct-13 2:53
memberErnst Sauer14-Oct-13 2:53 
AnswerRe: Errors & The only way is to edit the build.gradle file manually Pin
Raja.D.Singh14-Oct-13 8:10
memberRaja.D.Singh14-Oct-13 8:10 
GeneralRe: Errors & The only way is to edit the build.gradle file manually Pin
Ernst Sauer15-Oct-13 4:17
memberErnst Sauer15-Oct-13 4:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 9 Oct 2013
Article Copyright 2013 by Raja.D.Singh
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid