Вы находитесь на странице: 1из 19

3/9/12 Locaion API and Google Map in Andoid - Toial

1/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
Toial
232
www.bagittoda .com
Ads b Google
b Lars Vogel
Locaion API and Google Map in Andoid - Toial
La Vogel
Version 3.0
Copyright 2010 , 2011, 2012 Lars Vogel
15.02.2012
Revision Histor
Revision 0.1 15.06.2010 Lars
Vogel
created
Revision 0.2 - 3.0 18.06.2010 - 15.02.2012 Lars
Vogel
bugfixes and enhancements
Andoid Locaion API and Google Map
This tutorial describes the usage of the Android Location API, the usage of Google Maps and the Geolocation API. It
is based on Eclipse 3.7, Java 1.6 and Android 4.0 (Ice Cream Sandwich) (Gingerbread).
Table of Conen
1. Android Basics
2. Android Location API
2.1. Determine the current geolocation
2.2. LocationManager
2.3. LocationProvider
2.4. Selecting LocationProvider via Criteria
2.5. Proximity Alert
2.6. Forward and reverse Geocoding
2.7. Security
2.8. Prompt the user to Enabled GPS
3. Using GPS and setting the current location
Home Tutorials Trainings Books Social
3/9/12 Locaion API and Google Map in Andoid - Toial
2/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
3.1. Activating GPS on the emulator
3.2. Setting the geoposition
4. Tutorial: Using the Android Location API
4.1. Create Project
4.2. Add permissions
4.3. Activity
4.4. Run and Test
5. Google Maps
5.1. MapsView
5.2. MapsActivity
5.3. ItemizedOverlay and OverlayItems
5.4. maps library usage declaration
6. Device with Google API
7. Google Map key
8. Google Maps
8.1. Create Project
8.2. Google Map library
8.3. Overlays
8.4. Layout
8.5. Activity
8.6. Run and Test
9. Thank you
10. Questions and Discussion
11. Links and Literature
11.1. Source Code
11.2. Android Resources
11.3. vogella Resources
1. Andoid Baic
The following assumes that you have already basic knowledge in Android development. Please check the Android
development tutorial for the basics.
2. Andoid Locaion API
2.1. Deemine he cen geolocaion
Most Android devices allow to determine the current geolocation. This can be done via a GPS (Global Positioning
System) device, via cell tower triangulation or via wifi networks.
3/9/12 Locaion API and Google Map in Andoid - Toial
3/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
Android contains the andoid.locaion package which provides the API to determine the current geo position.
2.2. LocaionManage
The LocaionManage class provides access to the Android location service. This services allows to access
location providers, to register location update listeners and proximity alerts and more.
2.3. LocaionPoide
The LocaionPoide class provides location data via the Locaion class. The LocaionPoide class
is the superclass of the different location providers which deliver the information about the current location.
The Android device might have several LocaionPoide available and you can select which one you want to
use. In most cases you have the followng LocaionPoide available.
Table 1. LocaionPoide
LocaionPoide Decipion
network Uses the mobile network or WI-Fi to determine the best location. Might have a higher precision in
closed rooms then GPS.
gps Use the GPS receiver in the Android device to determine the best location via satellites. Usually
better precision then network.
passive Allows to participate in location of updates of other components to save energy
2.4. Selecing LocaionPoide ia Cieia
For a flexible selection of the best location provider use a Cieia object in which you can define how the
provider should be selected.
You can register a LocaionLiene object with the LocaionManage class to receive periodic updates
about the geoposition.
2.5. Poimi Ale
You can also register an Inen which allows to define a proximity alert, this alert will be triggered if the device
3/9/12 Locaion API and Google Map in Andoid - Toial
4/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
enters a area given by a longitude, latitude and radius (proximity alert).
2.6. Foad and eee Geocoding
The Geocode class allows to determine the geo-coordinates (longitude, laditude) for a given address and
possible addresses for given geo-coordinates.
This process is known as forward and reverse geocoding.
2.7. Seci
If you want to access the GPS sensor, you need the ACCESS_FINE_LOCATION permission. Otherwise you need
the ACCESS_COARSE_LOCATION permission.
2.8. Pomp he e o Enabled GPS
The user can decide if the GPS is enabled or now.
You can find out, if a LocationManager is enabled via the iPoideEnabled() method. If its not enabled you
can send the user to the settings via an Inen with the Seing.ACTION_LOCATION_SOURCE_SETTINGS
action for the andoid.poide.Seing class.

LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boo1ean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to displa a dialog and suggesting to
// go to the settings
1f (!enabled) {
Intent intent = neW Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);


Typically you would open an AlamDialog prompt the user and if he wants to enable GPS or if the application
should be canceled.
You cannot enable the GPS directly in your code, the user has to do this.
3. Uing GPS and eing he cen locaion
3/9/12 Locaion API and Google Map in Andoid - Toial
5/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
3.1. Aciaing GPS on he emlao
You need to activate GPS on your test device. If you test on the emulator and its not activated you "null" if you try to
use a LocaionManage.
The Google Map Acii should automatically activate the GPS device in the emulator but if you want to use the
location manager directly you need to do this yourself. Currently their seems to be an issue with this.
Start Google Maps on the emulator and request the current geo-position, this will allow you to activate the GPS.
Send new GPS coordinates to the Android emulator.
3.2. Seing he geopoiion
You can use the "DDMS" Pepecie of Eclipse to send your geoposition to the emulator or a connected
device. For open this Pepecie select Window Open Perspective Other DDMS.
In the Emulator Control part you can enter the geocoordinates and press "Send."
You can als set the geoposition the Android emulator via telnet. Open a console and connect to your device. The port
number of your device can be seen in the title area of your emulator.

telnet localhost 5554

Set the position via the following command.

3/9/12 Locaion API and Google Map in Andoid - Toial
6/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
geo fix 13.24 52.31

4. Toial: Uing he Andoid Locaion API
4.1. Ceae Pojec
Create a new project called "de.vogella.android.locationapi.simple" with the Activity called "ShowLocationActivity".
This example will not use the Google Map therefore, it also runs on an Android device.
Change your "main.xml" layout file from the "res/layout" folder to the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:orientation="horizontal" >
<TextView
android:id="@+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="Latitude: "
android:textSize="20dip" >
</TextView>
<TextView
android:id="@+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unknown"
android:textSize="20dip" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
3/9/12 Locaion API and Google Map in Andoid - Toial
7/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
<TextView
android:id="@+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="Longitute: "
android:textSize="20dip" >
</TextView>
<TextView
android:id="@+id/TextView04"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unknown"
android:textSize="20dip" >
</TextView>
</LinearLayout>
</LinearLayout>

4.2. Add pemiion
Add the following permissions to your application in your "AndroidManifest.xml" file
INTERNET
ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION
4.3. Acii
Change ShoLocaionAcii to the following. It queries the location manager and display the queried values
in the activity.

package de.vogella.android.locationsapi.simple;
1mpof android.app.Activity;
1mpof android.content.Context;
1mpof android.location.Criteria;
1mpof android.location.Location;
1mpof android.location.LocationListener;
1mpof android.location.LocationManager;
1mpof android.os.Bundle;
1mpof android.widget.TextView;
1mpof android.widget.Toast;
3/9/12 Locaion API and Google Map in Andoid - Toial
8/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
pub11c c1ass ShowLocationActivity exfends Activity 1mp1emenfs LocationListener {
p1vafe TextView latituteField;
p1vafe TextView longitudeField;
p1vafe LocationManager locationManager;
p1vafe String provider;

/** Called when the activity is first created. */
@Override
pub11c vo1d onCreate(Bundle savedInstanceState) {
supe.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = neW Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialie the location fields
1f (location != null) {
System.out.println("Provider " + provider + " has been selected.");
1nf lat = (1nf) (location.getLatitude());
1nf lng = (1nf) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
e1se {
latituteField.setText("Provider not available");
longitudeField.setText("Provider not available");


/* Request updates at startup */
@Override
pofecfed vo1d onResume() {
supe.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, fh1s);

/* Remove the locationlistener updates when Activit is paused */
@Override
pofecfed vo1d onPause() {
supe.onPause();
locationManager.removeUpdates(fh1s);

@Override
pub11c vo1d onLocationChanged(Location location) {
1nf lat = (1nf) (location.getLatitude());
3/9/12 Locaion API and Google Map in Andoid - Toial
9/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
1nf lng = (1nf) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));

@Override
pub11c vo1d onStatusChanged(String provider, 1nf status, Bundle extras) {
// TODO Auto-generated method stub

@Override
pub11c vo1d onProviderEnabled(String provider) {
Toast.makeText(fh1s, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();

@Override
pub11c vo1d onProviderDisabled(String provider) {
Toast.makeText(fh1s, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();


4.4. Rn and Te
If you using the emulator send some geo-coordinates to your device. These geo-coordinate should be displayed as
soon as you press the button.
5. Google Map
5.1. MapVie
Google provides via the com.google.andoid.map package a library for using the MapVie class in your
application. This maps allows embedded Google Maps into your application.
You require an additional key to use them. This key will be specified in the Vie which displays the map.
You need to add the following uses-library statement to your AndroidManifest.xml file. The project creation wizard
does this automatically if you select a Google API version.

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

3/9/12 Locaion API and Google Map in Andoid - Toial
10/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
The usage of MapVie requires the permission to access the Internet, as the data displayed in the MapVie is
downloaded from the Internet.
5.2. MapAcii
The MapAcii class extends the Acii class and provides the life-cycle management and the services
for displaying a MapVie widget.
MapActivity simplify the handling MapVie similar to LiAcii simplifies the usage of LiVie.
A MapVie is typically defined in the XML layout file used by the MapAcii and requires the API key in the
"android:apiKey" attribute. A MapVie can be used with other user interface components in the same layout.
The MapConolle class can be used to interact with the MapVie, e.g. by moving it. A Geopoin is a
position described via latitude and longitude.
5.3. IemiedOela and OelaIem
You can put instances of the Oela class on the map. Oela is the base class representing an overlay which
may be displayed on top of a map. To add an overlay, subclass this class, create an instance, and add it to the list
obtained from MapView.getOverlays().
ItemizedOverlay
is the base class for an Oela which consists of a list of OelaIem.
ItemizedOverlay
handles sorting north-to-south for drawing, creating span bounds, drawing a marker for each point, and maintaining a
focused item. It also matches screen-taps to items, and dispatches Focus-change events to an optional listener.
5.4. map liba age declaaion
You must declare that your application uses the com.google.andoid.map library in the application of your
AndroidManifest.xml file. Please note that the usage declaration must be in the application tag otherwise you get
jaa.lang.ClaNoFondEcepion for your Acii.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.locationapi.maps"
3/9/12 Locaion API and Google Map in Andoid - Toial
11/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<uses-library android:name="com.google.android.maps" >
</uses-library>
<activity
android:name="MapViewDemo"
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>
</manifest>

6. Deice ih Google API
In case you want to use Google Maps in your emulator you have to create a device which supports the Google API's.
This requires that you also install the "Google API". During device creation select the target Google API's in the
version of your SDK.
3/9/12 Locaion API and Google Map in Andoid - Toial
12/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
7. Google Map ke
To use Google Maps you need an additional key. See for following description:

http://code.google.com/android/add-ons/google-apis/mapkey.html

This process is a little bit time consuming and involves creating a value on the command line. This values is needed
as input for a website which allow to create the key.
3/9/12 Locaion API and Google Map in Andoid - Toial
13/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
8. Google Map
8.1. Ceae Pojec
Create a new Android project called "de.vogella.android.locationapi.maps" with an Acii called
"ShowMapActivity". Make sure to select the "Google API" als Target.
Add the following permissions to your application.
INTERNET
ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION
8.2. Google Map liba
You need to add the Google maps library to your application. Add "uses library" to "AndroidManifest.xml".

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.locationapi.maps"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<uses-library android:name="com.google.android.maps" >
</uses-library>
<activity
android:name="MapViewDemo"
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>
3/9/12 Locaion API and Google Map in Andoid - Toial
14/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
</manifest>

8.3. Oela
Create the following class. We will later use an image called "point". Put one icon with this name in your drawable
folders. If you don't know where to find icons, you can copy the icons the Android wizard created and placed in the
drawable folders.

package de.vogella.android.locationapi.maps;
1mpof android.graphics.drawable.Drawable;
1mpof com.google.android.maps.ItemizedOverlay;
1mpof com.google.android.maps.OverlayItem;
pub11c c1ass MyOverlays exfends ItemizedOverlay<OverlayItem> {
p1vafe sfaf1c 1nf maxNum = 3;
p1vafe OverlayItem overlays[] = neW OverlayItem[maxNum];
p1vafe 1nf index = 0;
p1vafe boo1ean full = false;
p1vafe MyOverlays itemizedoverlay;
pub11c MyOverlays(Drawable defaultMarker) {
supe(boundCenterBottom(defaultMarker));

@Override
pofecfed OverlayItem createItem(1nf i) {
efun overlays[i];

@Override
pub11c 1nf size() {
1f (full) {
efun overlays.length;
e1se {
efun index;


pub11c vo1d addOverlay(OverlayItem overlay) {
1f (index < maxNum) {
overlays[index] = overlay;
e1se {
index = 0;
full = true;
overlays[index] = overlay;

3/9/12 Locaion API and Google Map in Andoid - Toial
15/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
index++;
populate();


8.4. Lao
The next step requires that you have created a valid key for using the MapVie widget.
Change the "main.xml" layout file in your "res/layout" folder to the following. and replace "Your Maps API Key" with
your Google Maps API key.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainlayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<com.google.android.maps.MapView
android:id="@+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="Your Maps API Key"
android:clickable="true" />
</RelativeLayout>

8.5. Acii
Change your Acii to the following. This Acii use an LocaionLine to update the MapVie
with the current location.

package de.vogella.android.locationapi.maps;
1mpof android.content.Context;
1mpof android.graphics.drawable.Drawable;
1mpof android.location.Location;
1mpof android.location.LocationListener;
1mpof android.location.LocationManager;
1mpof android.os.Bundle;
1mpof android.widget.LinearLayout;
1mpof com.google.android.maps.GeoPoint;
1mpof com.google.android.maps.MapActivity;
3/9/12 Locaion API and Google Map in Andoid - Toial
16/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
1mpof com.google.android.maps.MapController;
1mpof com.google.android.maps.MapView;
1mpof com.google.android.maps.OverlayItem;
pub11c c1ass ShowMapActivity exfends MapActivity {
p1vafe MapController mapController;
p1vafe MapView mapView;
p1vafe LocationManager locationManager;
p1vafe MyOverlays itemizedoverlay;
pub11c vo1d onCreate(Bundle bundle) {
supe.onCreate(bundle);
setContentView(R.layout.main); // bind the laout to the activit
// create a map view
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// Either satellite or 2d
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, neW GeoUpdateHandler());
Drawable drawable = fh1s.getResources().getDrawable(R.drawable.point);
itemizedoverlay = neW MyOverlays(drawable);
createMarker();

@Override
pofecfed boo1ean isRouteDisplayed() {
efun false;

pub11c c1ass GeoUpdateHandler 1mp1emenfs LocationListener {
@Override
pub11c vo1d onLocationChanged(Location location) {
1nf lat = (1nf) (location.getLatitude() * 1E6);
1nf lng = (1nf) (location.getLongitude() * 1E6);
GeoPoint point = neW GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);

@Override
pub11c vo1d onProviderDisabled(String provider) {

@Override
pub11c vo1d onProviderEnabled(String provider) {
3/9/12 Locaion API and Google Map in Andoid - Toial
17/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml

@Override
pub11c vo1d onStatusChanged(String provider, 1nf status, Bundle extras) {


p1vafe vo1d createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = neW OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);


8.6. Rn and Te
Run and test your application. You should be able to zoom in and out and send new geocoordinates to your map via
the Emulator.
3/9/12 Locaion API and Google Map in Andoid - Toial
18/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
It will also draw Overlays on the Map.
9. Thank o
Please help me to support this article:

10. Qeion and Dicion
3/9/12 Locaion API and Google Map in Andoid - Toial
19/19 .ogella.de/aicle/AndoidLocaionAPI/aicle.hml
Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use
the www.vogella.de Google Group. I have created a short list how to create good questions which might also help
you.
11. Link and Lieae
11.1. Soce Code
Source Code of Examples
11.2. Andoid Reoce
Introduction to Android Development
Android Location API and Google Maps
Android Homepage
11.3. ogella Reoce
Eclipse RCP Training (German) Eclipse RCP Training with Lars Vogel
Android Tutorial Introduction to Android Programming
GWT Tutorial Program in Java and compile to JavaScript and HTML
Eclipse RCP Tutorial Create native applications in Java
JUnit Tutorial Test your application
Git Tutorial Put everything you have under distributed version control system

Вам также может понравиться