Showing current location using OnMyLocationChangeListener in Google Map Android API V2

February 28, 2013
By

In this article, we will create an Android application which will display current location in Google Maps using Google Maps Android API V2.

It also determines latitude and longitude of the current my location and displays it in a TextView.

The data contained in the TextView will be updated automatically as the current location is changed. The location change is tracked by implementing the callback interface OnLocationChangeListener.

This application is developed in Eclipse 4.2.1 with ADT plugin ( 21.1.0 ) and Android SDK ( 21.1.0 ) and is tested in a real Android Phone with Android ( 2.3.6 ).


1. Download and configure Google Play Services Library in Eclipse

Google Map for Android is now integrated with Google Play Services. So we need to set up Google Play Service Library for developing Google Map application in Android.

Please follow the given below link to setup Google Play Service library in Eclipse.

http://developer.android.com/google/play-services/setup.html

Note : Please ensure that, the latest version of Google Play Service Library is installed


2. Create a new Android Application Project namely “LocationInGoogleMapV2LocationChanged”

Create a new Android application project

Figure 1 : Create a new Android application project


3. Configure Android Application Project

Configure Android application project

Figure 2 : Configure Android application project


4. Design Application Launcher Icon

Design application launcher icon

Figure 3 : Design application launcher icon


5. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


6. Enter Main Activity Details

Enter MainActivity details

Figure 5 : Enter MainActivity details


7. Link to Google Play Services Library

Linking Google Play Services Library to this project

Figure 6 : Linking Google Play Services Library to this project


8. Get the API key for Google Maps Android API v2 

We need to get an API key from Google to use Google Maps in Android application. Please follow the given below link to get the API key for Google Maps Android API v2.

https://developers.google.com/maps/documentation/android/start


9. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup window, Click “Android Tools -> Add Support Library “



10. Update the file AndroidManfiest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationingooglemapv2locationchanged"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <permission
        android:name="in.wptrafficanalyzer.locationingooglemapv2locationchanged.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-permission android:name="in.wptrafficanalyzer.locationingooglemapv2locationchanged.permission.MAPS_RECEIVE"/>

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="in.wptrafficanalyzer.locationingooglemapv2locationchanged.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR_API_KEY"/>
    </application>

</manifest>

Note : Enter your api key in line 44, obtained in Step 8


11. Update the layout file activity_main.xml to display Google Map using SupportMapFragment


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/tv_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

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

</RelativeLayout>


12. Update the file src/in/wptrafficanalyzer/locationingooglemapv2locationchanged/MainActivity.java


package in.wptrafficanalyzer.locationingooglemapv2locationchanged;

import android.app.Dialog;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;

public class MainActivity extends FragmentActivity implements OnMyLocationChangeListener {

    GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else {    // Google Play Services are available

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            googleMap = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            googleMap.setMyLocationEnabled(true);

            // Setting event handler for location change
            googleMap.setOnMyLocationChangeListener(this);

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onMyLocationChange(Location location) {
        TextView tvLocation = (TextView) findViewById(R.id.tv_location);

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        // Setting latitude and longitude in the TextView tv_location
        tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );

    }
}


13. Enable GPS in the device from Settings



14. Running the application

Showing current location in Google Map Android API V2

Figure 7 : Showing current location in Google Map Android API V2


15. Download Source Code


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , ,

15 Responses to Showing current location using OnMyLocationChangeListener in Google Map Android API V2

  1. Tony Green on March 1, 2013 at 9:17 pm

    Yet another excellent tutorial. But this one I’m having trouble getting to work.

    In MainActivity.java, Eclipse is objecting to:

    import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;

    Saying it can’t resolve the import.
    I assume this is why it’s also objecting to:

    public class MainActivity extends FragmentActivity implements OnMyLocationChangeListener {

    and

    googleMap.setOnMyLocationChangeListener(this);

    Same problem both rolling my own and downloading your bundle. Probably me doing something stupid…

    Incidentally, if you’re looking for ideas for more of your superb tutorials, I’d love to see how to display markers from a Google Maps “My Places” map. I can display the markers in the Google maps app by importing them as a layer under “my maps”, but I’d love to be able to do the same in a standalone app (either linking to the saved map or grabbing a KML file over the network.

    Thanks again for some great tutorials – I’m learning a lot.

    • george on March 1, 2013 at 10:05 pm

      >> Saying it can’t resolve the import.
      OnMyLocationChangeListener is an interface available only with the latest version of Google Play services library ( Revision 5 ). So please upgrade your Google Play services library via Android SDK manager and then try again.

      • Tony Green on March 9, 2013 at 5:51 pm

        Spot on. Many thanks.

  2. Sultan Ishmuradov on March 8, 2013 at 2:36 am

    First of all i need to thank you for your great work but it doenst works onmy phone it gives me just white screen with + – zoom controls actually im woriking on this for 2 weeks still can do it i wrote different kind of codes get api v2 key even i reinstall eclipse adt my macos on computer still cant do it if i send you my codes can you help me plz its very important for me

    • Patrik on January 13, 2014 at 2:37 pm

      You tried to reinstall app in mobile phone ? if you have white screen problem can be just in API key try create another debug keystore

  3. Ron Coffee on March 15, 2013 at 12:51 am

    Having some issues the code: Even though my SDK has support lib rev 12, when I go to Add Android Support Library, I get an error of URL not found C:/. . . If my SDK Manager has it loaded already, why is Eclipse downloading a new one? One that it can’t find at that.
    secondly, I don’t get the option of the Google Play Services lib and no way to enter a path to that lib.
    Thirdly: I now see that there is a V3 for Google maps. Any updates for that?

    • Wacky on November 4, 2013 at 2:29 am

      V3 Google Api is JS library and not Native Android

  4. Ravi on April 15, 2013 at 5:36 pm

    I am usinhg this example and I get error in GoogleMap and SupportMapFragment,
    It gives like create class for Above.
    How can I solve this.?

  5. Abhishek on May 27, 2013 at 12:46 am

    Hi i have downloaded the code. but when i started executing the code. i am getting an error like this.

    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.wptrafficanalyzer.locationingooglemapv2locationchanged/in.wptrafficanalyzer.locationingooglemapv2locationchanged.MainActivity}: java.lang.ClassNotFoundException: in.wptrafficanalyzer.locationingooglemapv2locationchanged.MainActivity

  6. bacbim on June 19, 2013 at 8:01 pm

    Hello,when i’m imported your source code and it doesn’t work.then I created other a project follow your tutorial.But i have a problem.my project only show map and it can’t show current Location .although i enabled GPS in the device .Please help me? tell me how to resolved this problem.

  7. Kiran on November 21, 2013 at 10:26 pm

    We are doing our final year project on google maps API we used the code which you have given in the site but we are not able to get the maps in to the app no error is showing we have put the api key rest everything correctly . Please reply soon.

  8. sri on February 8, 2014 at 12:56 pm

    Am doing final year project on google map API v2 i need to traverse from one geo point(source) to other(destination) i need to guide the user like turn by turn. how to do that

  9. dawlaaa on April 23, 2014 at 10:50 pm

    I want to plot my track using GPS on Google Map v2
    Please Help :)

  10. AyamSakata on August 18, 2014 at 2:39 pm

    hello,first of all i want to thank you for your code however whenever i execute it either in an emulator or real device, it only pops out an error message saying “Unfortunately, Map has stopped”, I followed everything in your tutorial, I just don’t know What I did wrong, will you help me thanks a lot..

  11. naresh on March 2, 2016 at 4:24 pm

    I want to your code and iam trying for google map but not working. iam already create android google api key but my app not working so please help ….

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner