Click here to Skip to main content
15,067,832 members
Articles / Mobile Apps / Android
Posted 22 Sep 2010


135 bookmarked

GPSLocator - App to Find Current (Nearest) Location using GPS

Rate me:
Please Sign up or sign in to vote.
4.85/5 (47 votes)
27 Sep 2010CPOL8 min read
Android application to show current location in Google Maps using GPS
GPSLocator - Showing GPS Locations on Google Maps



One of the most fascinating features provided by a phone is GPS functionality (at least for me it is). I never realized that interacting with GPS functionality is so easy until I worked with it. This article is a way to help people realize the same. This article is targeted to a beginner who wants to implement GPS functionality and work with Google Maps API as well.

In this article, we will create a very simple application called GPSLocator. GPSLocator gets the Latitude and Longitude information from GPS and displays the exact (or nearest, at times) location in Google Maps.


For developing GPSLocator, we need the following applications pre-installed:

Apart from the above two things, we also require:

One Step at a Time

Explaining an application, specially developing an application is a complex task. We will try to break it down into multiple steps to make it easy to swallow. We will try to complete one step at a time and move towards our final application. So, let's get started.

Google Maps API key and KeyStore File

The first and foremost thing is getting a Google Maps API key. Getting one is relatively easy but it requires our application to be signed with a certificate and notify Google about Hash (MD5) fingerprint of the certificate. Now, the process can be further divided into two parts:

  • Creating a certificate and getting its MD5 fingerprint

    We can create a new certificate by using keytool.exe, found in bin directory of JDK installation path (something like C:\Program Files\Java\jdk1.6.0_21\bin). We need to pass some information and it will generate a keystore file (Public Key Storage Certificate File). One sample output is:

    Create new keystore file

    For developing and testing application, we usually sign the application in Debug mode. For this, we need to sign-up for Google Maps API with the debug certificate MD5 hash. The certificate used for this purpose is debug.keystore. It is usually located in:


    For finding the MD5 of a certificate, we run the command:

    keytool -list -alias androiddebugkey -keystore debug.keystore 
    -storepass android -keypass android

    The output of the command looks like:

    Get MD5 fingerprint of certificate

  • Signing up for Google Maps API

    Go to Maps API Key signup page and pass on MD5 key (highlighted above) and we get a Maps API key. The page also shows how to use API key in a MapView.

    Get Maps API Key

    For more details about getting Google Maps API key, check Obtaining a Maps API Key.

Create New Android Project

Create a new Android Project and provide the details as below. Also, make sure to select Build Target as Google APIs.

Create new Android Project

Click Finish and the project is created. Create a Run Configuration for the project to launch an AVD targeted to Google APIs (Check Prerequisite section). Also, make sure that version of Google APIs selected for AVD and Build Target is same. Some screenshots of the configuration are:

Run Configuration Android tab

Run Configuration Target tab

Try running the project with the specified configuration and it should show something like:

Basic output of GPSLocator

Add Google Map and Permissions

Before we can start using MapView control from Google APIs, we need to add the Google Maps External Library ( to the library. For adding a library to the project use uses-library tag. This tag needs to be added to AndroidManifest.xml. Apart from the library, we need to add relevant permissions as well. For adding permissions, we use uses-permission tag. For our application, we will add the following permissions:

  • android.permission.ACCESS_COARSE_LOCATION: Allows application to access coarse location (Cell ID, Wi-Fi etc.)
  • android.permission.ACCESS_FINE_LOCATION: Allows application to access GPS location.
  • android.permission.INTERNET: Allows application to open network sockets.

For more information about permissions, check Permissions.

The final AndroidManifest.xml should look like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />  
  <uses-permission android:name="android.permission.INTERNET" />
  <application android:icon="@drawable/icon" android:label="@string/app_name">
    <uses-library android:name="" />
    <activity android:name=".GPSLocatorActivity"
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />

Finally, add MapView control to main.xml under res/layout. The resultant code should look like:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

Show the Bare Minimum Google Map

In order to display Google Map view, we need to update our Activity class (GPSLocatorActivity). This class should extend MapActivity class in place of Activity class. We also need to import package to support MapActivity class. We also need to override isRouteDisplayed method of MapActivity class. This is fairly easy, just return false from the method. After all these modifications, should look like:

package com.VertexVerveInc.GPSLocator;

import android.os.Bundle;

public class GPSLocatorActivity extends MapActivity 
  public void onCreate(Bundle savedInstanceState) {
  protected boolean isRouteDisplayed() {
    return false;

Try running the application at this stage and it should show Google Map in the Emulator.

Basic Google Map view

Add Zoom (in/out) Controls

MapView class has an in-built method setBuiltInZoomControls. Invoking this method with true/false enable/disables Zoom in/out controls. In order to invoke this method, we need to find the instance of MapView class by calling findViewById with id of MapView control. Remember id="@+id/mapView" from the main.xml. One important thing to note here is that the zoom controls will become enable once we will touch/click the map view.

Change Map view and Zoom level

We can select, if we want to show Satellite, Traffic or Street view in maps. This is simply achieved by calling setSatellite, setStreetView and setTraffic methods. Another thing to do before we move further is zoom the map a bit. Why? Because the map view shown in the above output doesn't serve any purpose. In order to set zoom level of Map, we need an instance of MapController and we can call its setZoom method. So, let's update the onCreate method of GPSLocatorActivity class to incorporate all these changes.


private MapView mapView;
private MapController mapController;

public void onCreate(Bundle savedInstanceState) {
  mapView = (MapView) findViewById(;
  // enable Street view by default
  // enable to show Satellite view
  // mapView.setSatellite(true);
  // enable to show Traffic on map
  // mapView.setTraffic(true);
  mapController = mapView.getController();

Running the application at current stage produces the following output:

Google Map in Street View

Zoom in/out controls

Add GPS Location Mapping

Android provides location based services through LocationManager (package android.Location) class. This class provides periodical updates about the location of the device. In order to user LocationManager, we need to get a reference of LocationManager class by calling getSystemService method. Later on, we need to register for location updates by calling requestLocationUpdates method.

We need to create a class implementing abstract LocationListener class. This class will be registered with Location Manager to receive updates of location. We need to override all four methods of this class, namely onLocationChanged, onProviderDisabled/Enabled, and onStatusChanged. As we are just interested in getting location updates, we will modify the code of onLocationChanged to navigate to the new location received in the map view. This is achieved by calling animateTo method of MapController.

Let's add the bits of code to our project.

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

private LocationManager locationManager;
private LocationListener locationListener;

public void onCreate(Bundle savedInstanceState) {
  locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  
  locationListener = new GPSLocationListener();

private class GPSLocationListener implements LocationListener 
  public void onLocationChanged(Location location) {
    if (location != null) {
      GeoPoint point = new GeoPoint(
          (int) (location.getLatitude() * 1E6), 
          (int) (location.getLongitude() * 1E6));
          "Latitude: " + location.getLatitude() + 
          " Longitude: " + location.getLongitude(), 


On running the application, we see a message displaying information about the GPS location. We can skip to the Testing GPS functionality section to get this working. For more information about working with location, check Obtaining User Location.

Showing GPS Location information

Find Address for GPS Location

We can find information about an address if we know its latitude and longitude. For this purpose, we use Geocoder class and the process is known as Geocoding. We will call getFromLocation method of the class and will pass the point as a parameter. This method returns a List of Address which contains information about address of the specified location. We can combine the information to find the complete information about the point. For this purpose, we will add a method ConvertPointToLocation to GPSLocationListener class. ConvertPointToLocation returns a string object containing address of the location.

import android.location.Geocoder;
import android.location.Address;

private class GPSLocationListener implements LocationListener {
  public void onLocationChanged(Location location) {
    if (location != null) {
      String address = ConvertPointToLocation(point);
      Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
  public String ConvertPointToLocation(GeoPoint point) {   
    String address = "";
    Geocoder geoCoder = new Geocoder(
        getBaseContext(), Locale.getDefault());
    try {
      List<Address> addresses = geoCoder.getFromLocation(
        point.getLatitudeE6()  / 1E6, 
        point.getLongitudeE6() / 1E6, 1);
      if (addresses.size() > 0) {
        for (int index = 0; 
	index < addresses.get(0).getMaxAddressLineIndex(); index++)
          address += addresses.get(0).getAddressLine(index) + " ";
    catch (IOException e) {        
    return address;

Running the application shows an address on the map in place of longitude and latitude values.

Showing GPS Location information

Add a Location Marker

A lot many times, we want to add a marker (image) to the location because the small circle (shown in maps by default) is sometimes useless. In order to add a marker, add a drawable resource to the project. We can import any image (which we want to use) to our project (simple drag and drop also works). Add the image to res/drawable folder.

In order to add a location marker to the map, we need to create a class which extends Overlay ( package) class. We need to override draw method of the class and do some custom painting. The MapOverlay class looks like:


private class GPSLocationListener implements LocationListener 
  public void onLocationChanged(Location location) {
      // add marker
      MapOverlay mapOverlay = new MapOverlay();
      List<Overlay> listOfOverlays = mapView.getOverlays();
      String address = ConvertPointToLocation(point);
      Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();


class MapOverlay extends Overlay
  private GeoPoint pointToDraw;

  public void setPointToDraw(GeoPoint point) {
    pointToDraw = point;

  public GeoPoint getPointToDraw() {
    return pointToDraw;
  public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
    super.draw(canvas, mapView, shadow);           

    // convert point to pixels
    Point screenPts = new Point();
    mapView.getProjection().toPixels(pointToDraw, screenPts);

    // add marker
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),;
    canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null);    
    return true;

Yes, let's run this application and as expected it should show a marker at the current GPS location.

Showing Location Marker

Testing GPS Functionality

How can we test GPS functionality when we don't have any GPS in our computer? Well, this is really tricky but Developers at Google already thought about this problem. By this I mean, Yes, we have a way to interact with GPS on the emulator. We can simulate GPS location change in emulator. We can control and query the running instance of emulator with console (telnet). On a command prompt enter "telnet localhost <port>" command to connect to the console. Port number is usually displayed in the title bar of the emulator. For example, for me it is: 5554.

Showing Location Marker

We can change the GPS location by sending geo fix command. We need to pass longitude and latitude values along with it. For example, in order to change our current location to Seattle (longitude: -122.332071, latitude: 47.60621), we send 'geo fix -122.332071 47.60621' from the console. For more information about communicating with console, check Android Emulator.


Working with GPS and Google Maps API both is easy, entertaining and creative as well. GPSLocator is my first attempt to make my fellow developers aware of the same fact. Please provide your feedback and suggestions. Do I need to mention that you can rate my article as well, if you liked it.


  • Initial draft: Sep 22, 2010
  • Updated Google APIs link: Sep 27, 2010


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


About the Author

The Manoj Kumar
Team Leader
India India

Manoj Kumar is a Humble Programmer and a trainer having dozens of trainings, publications and articles to his wallet.

His programming adventures began with Basic at an age of 11. Being a mathematician at core, soon he started looking for some more and moved to assembly language, later to C, C++, VC++ and finally to .Net.

He started his professional career as a VC++ 6 trainer, moved to embedded systems and device driver development, then to complex biological systems and finally moved to pure application development.

He has been teaching and training people for more than 12 years on a wide range of topics including Mathematics, Algorithms, Data Structures, C, C++, VC++, MFC, C#, Design Patterns and now a days he is working extensively with Visual Studio and .Net framework which includes VSX, WPF, Silverlight, WCF, WF, XAML and RIAs.


  • Ideablade RIA Service Challenge winner
  • Visual Studio 2010 Extension Contest winner (Best Use of Editor)

Visit my website and blog or drop me a mail.

Feel free to connect with me on Linkedin.

Comments and Discussions

Questionsir?? Pin
bryanjaysena@yahoo.com18-Aug-16 19:07
Memberbryanjaysena@yahoo.com18-Aug-16 19:07 
QuestionAssisted GPS Pin
Member 1263023011-Jul-16 20:39
MemberMember 1263023011-Jul-16 20:39 
QuestionQuestion On google maps Pin
Member 1206893218-Oct-15 20:08
MemberMember 1206893218-Oct-15 20:08 
Questionpackage Pin
Member 119505321-Sep-15 2:07
MemberMember 119505321-Sep-15 2:07 
GeneralMy vote of 1 Pin
anupama.k.sinha22-Feb-15 18:23
Memberanupama.k.sinha22-Feb-15 18:23 
QuestionHelp needed for GPS using QT Android SDK Pin
gilgamash15-Oct-14 21:29
Membergilgamash15-Oct-14 21:29 
QuestionGetting only Box Pin
Member 1058789223-Aug-14 7:56
MemberMember 1058789223-Aug-14 7:56 
Questionnot showing current location Pin
Member 1101008119-Aug-14 19:09
MemberMember 1101008119-Aug-14 19:09 
Bugwhat is the command for generate certification for API in jdk7 using commandline Pin
Member 1096789829-Jul-14 22:23
MemberMember 1096789829-Jul-14 22:23 
Questionnot working Pin
Member 107215113-Apr-14 3:23
MemberMember 107215113-Apr-14 3:23 
QuestionHI Pin
Mohsin Azam30-Nov-13 6:19
MemberMohsin Azam30-Nov-13 6:19 
QuestionMessage Closed Pin
10-Oct-13 22:41
Memberkasun61810-Oct-13 22:41 
AnswerRe: Best GPS based system example souce code Pin
The Manoj Kumar15-Oct-13 17:29
MemberThe Manoj Kumar15-Oct-13 17:29 
QuestionThe application stopped unexpectedly.please try again Pin
Member 102233203-Sep-13 6:02
MemberMember 102233203-Sep-13 6:02 
QuestionClass referenced was not found? Pin
Member 1023020431-Aug-13 22:16
professionalMember 1023020431-Aug-13 22:16 
GeneralMy vote of 5 Pin
JasminHan29-Jul-13 16:57
professionalJasminHan29-Jul-13 16:57 
GeneralRe: My vote of 5 Pin
The Manoj Kumar30-Jul-13 6:28
MemberThe Manoj Kumar30-Jul-13 6:28 
Questionkeytool error Pin
Member 865772927-Jul-13 3:35
MemberMember 865772927-Jul-13 3:35 
AnswerRe: keytool error Pin
The Manoj Kumar30-Jul-13 6:32
MemberThe Manoj Kumar30-Jul-13 6:32 
GeneralGPS Pin
A. Prasad De Silva2-Mar-13 20:25
MemberA. Prasad De Silva2-Mar-13 20:25 
GeneralRe: GPS Pin
The Manoj Kumar26-Apr-13 16:55
MemberThe Manoj Kumar26-Apr-13 16:55 
GeneralGood one Pin
Bandi Ramesh16-Feb-13 2:07
MemberBandi Ramesh16-Feb-13 2:07 
GeneralRe: Good one Pin
The Manoj Kumar26-Apr-13 16:55
MemberThe Manoj Kumar26-Apr-13 16:55 
Questionquery Pin
girish sadariya1-Feb-13 23:01
Membergirish sadariya1-Feb-13 23:01 
AnswerRe: query Pin
The Manoj Kumar26-Apr-13 16:57
MemberThe Manoj Kumar26-Apr-13 16:57 

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.