-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
1/12
Q&A forums lounge
Rate this:Raja.D.Singh, 9 Oct 2013 CPOL
Download source 4.01 MB
A GPS Location Plotting Android Application
Develop an Android application that plots user location on a map
continuously.
IntroductionRecently, I was tasked with writing an application
that heavily relied on GPS and mapping of custom hardwaredevices
that were built with locationaware components. Even though I have
been using Eclipse for these tasksfor quite some time, Android
Studio's glittering new features and ease of use caught my
attention to try it outfor the task. During the few weeks I had
worked with Android Studio and with Google Maps Android API V2,
Ilearned some lessons that are worth sharing, so that others need
not reinvent the wheel and avoid the knownpitfalls on their
quest.
4.59 36 votes
11,471,403 members 62,910 online Sign in
articles
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
2/12
In this article, we will try to focus on developing an Android
application that uses Google Maps Android APIV2, using Android
Studio IDE. Very recently Google deprecated and as of March 18th,
2013, stopped issuingAPI keys for Google Maps Android V1 and
started recommending V2. A lot of documentation, books andother
resources on the web discuss doing things that are centered around
V1 and it is daunting for a newcomer to sieve through all that and
get some useful information on developing applications using API
V2. Toadd to the confusion, there is not very many resources on the
web that discusses using Android Studio forsuch development. Let us
hope to fill that gap here.
BackgroundGoogle announced on May 16th, 2013, at their Google
I/O conference, Android Studio as their IntegratedDevelopment
Environment, IDE, of choice to develop Android Applications.
Android Studio is essentiallyInettliJ IDEA from JetBrains, but is
heavily focused on the development of Android applications. Android
Studiouses Gradle for dependency resolution and most of the project
management tasks in the IDE. Android Studiois available for
download from here.. Android Studio has an automatic software
updater that automaticallychecks for new updates and updates the
IDE to the latest version. As of this writing, the newest version
was0.2.11, Build AI132.855830.
Prior to Android Studio and even after, majority of developers
use Eclipse as a fundamental platform forAndroid application
development. Eclipse is an excellent platform that provides a great
IDE for softwaredevelopment in Java, C++ and various other
languages.
Create an Android applicationI am going to assume that the
reader is familiar with the structure of an Android Application and
the filesinvolved in making an application, in addition to the
concepts of Activity, Intent, Activity life cycle and variousstates
of it during its existence, Resource files and Strings etc. There
are many books and text available off theweb on Android Application
development concepts. We are going to focus on a specific
application with aspecific tool in this article. I have used a
Linux machine with Android Studio. The information in this
articlecould 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, whenstarted. You are presented
with a dialog as shown below. Fill in the Name of the application
with anymeaningful name such as GPSPlotter, in this example. Fill
in the package name for your code, such
ascom.siriusmicrotech.gpsplotter, in this example. This will be the
application name that is going to be used forAPI Key generation
that we discuss later in the article. Please note that the Minimum
required SDK is selectedas AP11, since Google Maps Android API V2
requires SDK greater than AP8 for it to work. Then click next
toaccept all the defaults through the subsequent screen presented
until the project is created by clicking onFinish.
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
3/12
Here is the screen shot of the skeletal project we have
created.
Offe
rsW
izar
dAd
s
Offe
rsW
izar
dAd
s
xadbyOffersWizard
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
4/12
Even though there are many files created in this process,
luckily, we are going to focus on only the followingfive files:
MainActivity.javaactivity_main.xmlstrings.xmlAndroidManifest.xmlbuild.gradle
Location ProvidersBefore we start to modify these files, let us
discuss some background on why we do what we do in thefollowing
sections. Android devices are equipped with GPS hardware. Android
provides a very straight forwardAPI to access Location information
derived from GPS hardware along with WiFi and Cellular
networkconnection sources that helps provide location information.
Since an application should be able to access thecurrent location
information of the device, we need to get the users permission for
the application to accessthis 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 theapplication to access
such as accessing internet, since Maps are to be downloaded from
Internet, accessingStorage, since Maps need to be cached and for
accessing Location providers such as GPS and other forms oflocation
services. Android Maps also needs OpenGL. Here are the lines added
to our AndroidManifest.xml filejust above the tag.
Hide Copy Code
Using Google Maps Android API V2 in our CodeSince Google Maps
Android API V2 is not included in the Android Development Kit ADK
and instead it isincluded in the Google Play Services API, we need
to install it separately. Fire up SDK manager and go to theExtras
section and check against the Google Play Services and Google
Repository and click Install Packages.
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
5/12
Once Google Play Services API is installed, we need to include
it in our project. The very nice tutorial atGoogle's android
developer site is written targeting Eclipse as the platform, it
suggests including a referenceto the Google Services Library by
Importing it into the workspace. This will not work with Android
Studio sinceGradle is used for dependency resolution here. So, we
need to edit build.gradle file as follows, by adding asingle line
in the dependency section of it. Please note, as of this writing,
the UI can not be used to add thisdependency for Gradle. The only
way is to edit the build.gradle file manually. However, one must
realize thatthis is much simpler than the solution discussed at the
developer's site.
Hide Copy Code
dependencies{//GooglePlayServicescompile'com.google.android.gms:playservices:3.2.65'//SupportLibrarycompile'com.android.support:appcompatv7:18.0.0'}
Now, to show a map in our application, we need a Fragment in our
layout. This is done by replacing theTextView section in the
activity_main.xml file with a Fragment section as follows:
Hide Copy Code
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
6/12
android:layout_width="match_parent"android:layout_height="match_parent"/>
And modifying MainActivity.java by deriving the MainActivity
class from FragmentActivity instead ofActivity, as follows:
Hide Copy Code
publicclassMainActivityextendsFragmentActivity
Now, technically we have everything on the device side of the
application. However, the Map has to comefrom the Cloud. To access
the Maps from the cloud, we need a special authentication key
called API Key, givento our application by the Google Cloud
services, where the Maps are served from. Even though it sounds
verycomplicated, 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 certificateshould be
used for generating this key, only if we are going to publish the
application. Once this key isobtained, copy this key into the
AndroidManifest.xml file as follows, just above tag.
Hide Copy Code
Please note, it is much simpler to connect an Android device to
the PC and install this application on it andtest it than to use
the Emulator. However, please remember to enable USB debugging on
the device. If yourdevice is running Jelly Bean, by default,
Developer Options section of the Settings menu is hidden to
protectthe user from doing any harm with this feature. Go to System
Settings Menu and scroll all the way down to seeif you see
Developer Options listed. If it is not listed, to bring the
Developer Options to view, select AboutPhone menu and scroll all
the way down where you see Build Number. Keep tapping on Build
Number severaltimes rapidly until you see that Developer Options
are enabled. Go into Developer Options menu and enableUSB 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 wentwell, you would see a
Google map displayed centered somewhere around the continent of
Africa! That's notmuch work, is it.
Displaying and following our location on the MapDisplaying 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
theAndroidManifest.xml file earlier on. The GoogleMap class
provides a neat integration many features, includinglocation
tracking. So, the sequence of tasks here are to
get the object reference for the map we just displayedtie up a
location listener to this map that responds to location changed
events from the locationservicesfocus our location on the map
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
7/12
We can obtain the map object reference by getting the reference
to the Fragment that we inserted in thelayout file as follows:
Hide Copy Code
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 asfollows. Note, we check for
null since the map may not be available before it is rendered
completely.
Hide Copy Code
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 fromlocation services. The
recommended method for doing this is to setup a location client for
the locationservices within our Main Activity with the following
code
Hide Copy Code
myLocationClient=newLocationClient(getApplicationContext(),this,this);//oncewehavethereferencetotheclient,connectitif(myLocationClient!=null)myLocationClient.connect();
The LocationClient object constructor takes three parameters,
the first is the application context and thesecond is the object
that implements Connection callbacks, such as establishment of
connection andDisconnection, and the third is the object that
implements Connection failure listener. Since we pass thereference
to the MainActivity object as the two call back inputs, we have to
implement those methods inour MainActivity class. Once we modify
our MainActivity class definition line as follows to implementthose
two interfaces and the LocationListener interface. Android Studio
will prompt us to implement therequired methods and will
automatically populate our class with the methods.
Hide Copy Code
publicclassShowMeOnMapextendsFragmentActivityimplementsGooglePlayServicesClient.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:
Hide Copy Code
@OverridepublicvoidonConnected(Bundlebundle){}
@OverridepublicvoidonDisconnected(){
}
@OverridepublicvoidonLocationChanged(Locationlocation){
}
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
8/12
@OverridepublicvoidonConnectionFailed(ConnectionResultconnectionResult){
}
As the names suggests, OnConnected is fired when the the service
is connected to our LocationClientobject. Here is where we have to
register our LocationListener to listen for location updates. So,
we editthis method body as follows
Hide Copy Code
@OverridepublicvoidonConnected(Bundlebundle){myLocationClient.requestLocationUpdates(REQUEST,this);}
As you already know, the this in the requestLocationUpdates call
is the reference to our MainActivitysince we are implementing the
LocationListener Interface here. The first parameter is
theLocationRequest object that sets options for the location
updates such as update frequency, accuracy etc.This is defined as
follows:
Hide Copy Code
privatestaticfinalLocationRequestREQUEST=LocationRequest.create().setInterval(5000)//5seconds.setFastestInterval(16)//16ms=60fps.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
In this application, we do not do anything for onDisconnected()
and onConnectionFailed() methodsand we leave them alone.
Once all these are setup, we are now ready to update our
location on the map whenever we receive a newlocation update from
the Location service through the
onLocationChanged(Locationlocation) methodthat we registered with
the LocationClient. OnLocationChanged is called back with Location
parameterthat gives as our current location. To move our map to
show our current location or any other location in theview. The map
view is modeled as a camera looking down on a flat plane. The
position of the camera andhence the rendering of the map is
specified by latitude, longitude, zoom, tilt, and bearing of the
location tobe shown. So, to show a given location on map, we update
the camera to that location. The safest way tomove camera to our
location is to use moveCamera() method in the GoogleMap class with
callbacks asfollows. The callbacks prevent the situation where the
map is not rendered completely and we are attemptingto update the
camera.
Hide Copy Code
myMap.moveCamera(CameraUpdateFactory.newCameraPosition(newCameraPosition.Builder().target(newLatLng(lat,lng)).zoom(15.5f).bearing(0).tilt(25).build()),newGoogleMap.CancelableCallback(){@OverridepublicvoidonFinish(){//YourcodeheretodosomethingaftertheMapisrendered}
@OverridepublicvoidonCancel(){
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
9/12
//YourcodeheretodosomethingaftertheMaprenderingiscancelled}});
In essence, what we have done so far should result in an
application that loads a map and shows our positionon it with a
blue arrow. This icon will track our location on the map as we move
around. However, we haveneglected some of the details, for the sake
of simplicity here. For instance, we have neglected the life
cycleevents of the MainActivity where is could be Paused and
Resumed etc. In the event of another activitydisplayed over our
MainActivity,preventing it from displaying, our MainActivity will
be Paused andsent to the background and an onPause()event is
generated. When the user gets back to our activity, it willbe
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 updateswhen sent to background and not displayed and
enable back again when resumed. This is done by overridingonPause()
and onResume() methods of the MainActivity. Please refer to the
complete application in thesource code bundle.
To use the source code and create an application for your own,
please follow these steps:
1. Unzip the source in a folder2. 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 andchange the line "package
com.siriusmicrotech.gpsplotter with your package name that you used
duringyour new project creation.
4. Copy the contents of activity_main.xml file from the source
you unzipped and paste it in your newactivity_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 filereplacing contents
entirely.
6. Do the same for AndroidManifest.xml file. However, here, you
have to change the third line from top toreplace
com.siriusmicrotech.gpsplotter with your package name and under the
tag, change
android:name="com.siriusmicrotech.gpsplotter.MainActivity" with
youractivity name.
7. Get your API key from Google Could Services8. 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 InterestThings to pay attention to Get the latest
version of Android Studio build. If you decided to use
AndroidStudio, do not research on the internet for solutions, since
almost all the text is written for Eclipse. There is asignificant
change in the way things are done in Google Maps Android API V2
than it was done in V1. Most ofthe 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
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
10/12
Raja.D.SinghFounder Sirius Microtech LLC United States
Raja.D.Singh is one of the Founders of Sirius Microtech LLC, a
Los Angeles based technology companydedicated to provide Innovative
Engineering services and excellent, standards compliant solutions
forproblems faced by Small to Medium sized engineering
organizations. Sirius specializes in New Productdevelopment for
Industrial Automation, Robotics, Alternative Energy and Real Time
Embedded Systems.
Follow on LinkedIn
Search Comments Go
This article, along with any associated source code and files,
is licensed under The Code Project Open LicenseCPOL
Share
About the Author
Comments and Discussions
You must Sign In to use this message board.
First Prev Next
EMAIL
GPS Member 11587922 7Apr15 7:06
How to rotate marker ?
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
11/12
Permalink | Advertise | Privacy | Terms of Use | Mobile Web01 |
2.8.150516.1 | Last Updated 9 Oct 2013 Select Language
Article Copyright 2013 by Raja.D.SinghEverything else Copyright
CodeProject, 19992015
Layout: fixed | fluid
Refresh 1 2 3 Next
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch
threads, Ctrl+Shift+Left/Right to switch pages.
Member 11072073 6Jan15 23:31
Is it possible to do this in offline?? Vijaydhas 4Nov14
20:41
Great Work + Small Question Member 10002938 8Oct14 1:10
Symbol 'R' error Kinrob 12Jul14 1:49
how do i run the proyect? Member 10914529 3Jul14 10:24
RE: Build gradle error Tontoy 12Jun14 19:11
The Download link appears to be broken Michael B Pliam 12May14
12:38
Compatibility with Eclipse MJR4PJCT 29Jan14 14:11
Re: Compatibility with Eclipse Dirk Diggler 4Jun14 7:24
-
5/20/2015 AGPSLocationPlottingAndroidApplicationCodeProject
http://www.codeproject.com/Articles/665527/AGPSLocationPlottingAndroidApplication
12/12