Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

A GPS Location Plotting Android Application

4.55/5 (51 votes)
9 Oct 2013CPOL13 min read 389K   47K  
Develop an Android application that plots user location on a map continuously.

Sample Image

Introduction

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.

Background

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:

  • MainActivity.java
  • 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="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!-- 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. -->
    <uses-feature
        android:glEsVersion="0x00020000"
        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.

Java
dependencies {
    // Google Play Services
    compile 'com.google.android.gms:play-services:3.2.65'
    // Support Library
    compile 'com.android.support:appcompat-v7:18.0.0'
}

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:

XML
<fragment
        class="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

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

Java
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.

XML
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            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:

Java
myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap(); 

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. -

Java
if(myMap != null)
{
    myMap.setMyLocationEnabled(true);
} 

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

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

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.

Java
public class ShowMeOnMap extends FragmentActivity
        implements GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener{ 

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

Objective-C
@Override
    public void onConnected(Bundle bundle) {
}

@Override
public void onDisconnected() {

}

@Override
public void onLocationChanged(Location location) {

}

@Override
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

Java
@Override
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:

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

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.

Java
myMap.moveCamera(CameraUpdateFactory.newCameraPosition(
           new CameraPosition.Builder().target(new LatLng(lat, lng))
        .zoom(15.5f)
        .bearing(0)
        .tilt(25)
        .build()
), new GoogleMap.CancelableCallback() {
    @Override
    public void onFinish() {
        // Your code here to do something after the Map is rendered
    }

    @Override
    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 MainActivity.java from the source you unzipped and paste it in your new MainActivity.java 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.  

License

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