Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

How to show your current location in a map

Published? false
FormatLanguage: WikiFormat

Problem:

You want to see where you are in a map using the built-in GPS in Android devices

Solution:

We can take advantage of the Google APIs and Location-Based Services to allow people to find their friends, find relevant places and many more. In this snippet of code, we can read the GPS location and see where we are located in a map called from the internet.

Discussion:

+Warning+ The Google Maps V1 API is deprecated; new code should use the V2 API discussed in Recipes 4285 and 4297.

This example of code shows how to create a MapActivity to show where are we located. Also, we're going to add some permissions to allow our project read the latitude and longitude based in the Google Maps API.

Step 1 Create a new project called MyCurrentLocation with an Activity called MyCurrentLocation. Because we need to obtain the Latitude and Longitude from the GPS, we need to add the following permissions in the Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.androidtitlan.mycurrentlocation"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MyCurrentLocation"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

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