Showing current location in Google Maps with GPS and LocationManager in Android

September 28, 2012
By

In this article, we will create an Android application which will display latitude and longitude of the current location in a text view and corresponding location in the Google Map. The current location will be retrieved using GPS and LocationManager API of the Android.

This application is developed in Eclipse ( 4.2.0) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 ).

Update : A upgraded version of this application ( using Google maps Android API V2 ) is discussed in the article titled “Showing current location in Google Maps using API V2 with SupportMapFragment” .


1. Create a new Android application project namely “LocationInGoogleMap”

New Andriod Application Project

Figure 1 : New Andriod Application Project


2. Design application launcher icon

Design application launcher Icon

Figure 2 : Design application launcher Icon


3. Create a blank activity to define the class MainActivity

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete Android’s backward compatibility support library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Obtain Google’s Map Key

Google’s Map Key for the Android application will be available here.

The map key obtained has to be entered as the value of the attribute android:apiKey in the layout file res/layout/activity_main.


7. Create a new folder namely drawable under the folder “res”


8. Download the given below image file namely “cur_position.png” to the folder “res/drawable”


9. Update the file res/values/strings.xml


<resources>
    <string name="app_name">LocationInGoogleMap</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Current Location in Google Map</string>
</resources>


10. Update the file res/layout/activity_main.xml


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

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

    <com.google.android.maps.MapView
        android:id="@+id/map_view"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="0u7AJChI1NV8vCpj21C0Cq8YnNMrB6YMgigu0GA"
        android:clickable="true"
        android:layout_below="@id/tv_location" />

</RelativeLayout>

Note : Replace the value of android:apiKey with the Google Map Key obtained in Step 6


11. Create the class CurrentLocationOverlay in the file src/in/wptrafficanalyzer/locationingooglemap/CurrentLocationOverlay.java


package in.wptrafficanalyzer.locationingooglemap;

import java.util.ArrayList;

import android.graphics.drawable.Drawable;
import android.util.Log;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;

public class CurrentLocationOverlay extends ItemizedOverlay<OverlayItem> {

    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

    public CurrentLocationOverlay(Drawable defaultMarker) {
        super(boundCenterBottom(defaultMarker));
    }

    // Executed, when populate() method is called
    @Override
    protected OverlayItem createItem(int arg0) {
        return mOverlays.get(arg0);
    }

    @Override
    public int size() {
        return mOverlays.size();
    }

    public void addOverlay(OverlayItem overlay){
        mOverlays.add(overlay);
        populate(); // Calls the method createItem()
    }

    @Override
    protected boolean onTap(int arg0) {
        Log.d("Tapped", mOverlays.get(arg0).getSnippet());
        return true;
    }
}

12. Update the class MainActivity in the file src/in/wptrafficanalyzer/locationingooglemap/MainActivity.java


package in.wptrafficanalyzer.locationingooglemap;

import java.util.List;

import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MainActivity extends MapActivity implements LocationListener {

    private MapView mapView;

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

        // Getting reference to MapView
        mapView = (MapView) findViewById(R.id.map_view);

        // Setting Zoom Controls on MapView
        mapView.setBuiltInZoomControls(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if(location!=null){
            onLocationChanged(location);
        }

        locationManager.requestLocationUpdates(provider, 20000, 0, this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

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

        // Getting latitude
        double latitude = location.getLatitude();

        // Getting longitude
        double longitude = location.getLongitude();

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

        // Creating an instance of GeoPoint corresponding to latitude and longitude
        GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));

        // Getting MapController
        MapController mapController = mapView.getController();

        // Locating the Geographical point in the Map
        mapController.animateTo(point);

        // Applying a zoom
        mapController.setZoom(15);

        // Redraw the map
        mapView.invalidate();

        // Getting list of overlays available in the map
        List<Overlay> mapOverlays = mapView.getOverlays();

        // Creating a drawable object to represent the image of mark in the map
        Drawable drawable = this.getResources().getDrawable(R.drawable.cur_position);

        // Creating an instance of ItemizedOverlay to mark the current location in the map
        CurrentLocationOverlay currentLocationOverlay = new CurrentLocationOverlay(drawable);

        // Creating an item to represent a mark in the overlay
        OverlayItem currentLocation = new OverlayItem(point, "Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);

        // Adding the mark to the overlay
        currentLocationOverlay.addOverlay(currentLocation);

        // Clear Existing overlays in the map
        mapOverlays.clear();

        // Adding new overlay to map overlay
        mapOverlays.add(currentLocationOverlay);

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
}


13. Update the file AndroidManifest.xml


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.wptrafficanalyzer.locationingooglemap"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <uses-library android:name="com.google.android.maps" />

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
        </activity>
    </application>
</manifest>


14. Enable GPS in the emulator or device from Settings

Enabling GPS in the Device

Figure 5 : Enabling GPS in Google APIs emulator for API Level 4


15. Set Latitude and Longitude of the location in Eclipse -> DDMS ( Perspective ) to run  this application in the emulator

Setting  Latitude and Longitude in Eclipse -> DDMS

Figure 6 : Setting Latitude and Longitude in Eclipse -> DDMS


16. Screenshot the application

Screenshot of the application executed in Emulator

Figure 7 : Screenshot of the application executed in Google APIs emulator for API Level 4


17. Download


18. Reference

http://developer.android.com/guide/index.html


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: , , , , , , , , ,

13 Responses to Showing current location in Google Maps with GPS and LocationManager in Android

  1. venugopal on November 21, 2012 at 1:04 pm

    Hi,
    Thank you for giving such good code and good explination in the same way I want to display the current adress please help me soon… Thanks

    • venugopal on November 27, 2012 at 7:30 pm

      can u help me ..I have saved the start,addwaypoint,stop for current location in database..now I want to display address and i want to show the view in map

    • ram on December 3, 2012 at 2:30 pm

      Hi Mr. George,
      Thank you for giving such good code and good explanation
      this is amazing think that any person giving free of cost facilities for programmer. all the developers should give many-2 thanks to Mr. George.
      Thanks

  2. venugopal on November 23, 2012 at 6:25 pm

    hi,
    can help me how to add different waypoints in gps with good explination

  3. ram on December 3, 2012 at 2:32 pm

    Hi Mr. George,

    I want to show multiple location in given region radius like 1000 etc
    please help me

    Thanks

  4. GauravKumawat on January 9, 2013 at 10:41 am

    hiii..george…
    i want to show the information of a location at given latitude and longitude in a view (can be a rectangle or circle) using overlay …….can u please help me out..thanks in adv.

  5. sourabh on January 20, 2013 at 1:00 pm

    thanks george…..
    u solved our big problem… :)

  6. ramesh on January 31, 2013 at 4:56 pm

    Hi,
    I tested ur code on my device. Its not returning lat&long at first time switch on device.

    when i went to disable/enable wifi button.. and checked ur sample application. it returns lat&long correctly..

    I checked with google android sample code.. This also works as like your code. it returns lat&long only after disable/enable wife.

    developer.android.com/shareables/training/LocationAware.zip

    Note:- This happens only if i restart the device.

    please provide a solution to get lat&long. when i launch app after restart.

  7. AYAN SINHA on February 25, 2013 at 7:18 pm

    Hi George,

    I am in a very difficult situation of how to get google directions in my android app. I dont want to show it inside google map but in my map. As I have searched there are no api’s for directions. So please help.
    Thanks in advance.

    ~Ayan

  8. Joseph Kenny on February 28, 2013 at 10:00 pm

    Hi,
    im using your code to learn how to use google api.

    However i keep getting errors to do with java.security.messagedigest???

    Any ideas???

  9. Mudassar Ahmed on March 16, 2013 at 3:26 am

    I am getting errors on
    mapView = (MapView) findViewById(R.id.map_view);
    error : map_view cannot be resolved or is not a field
    TextView tvLocation = (TextView) findViewById(R.id.tv_location);
    error :tv_location cannot be resolved or is not a field

    kindly help me

  10. Sachin on May 1, 2013 at 3:51 pm

    Can any one tell how to implement tracker api for my website project(Asset tracking system) in asp.net

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