You are on page 1of 50

Chapter 07

Location and Maps

Tagele B.

1
Android: Localization basics
Geolocalization Identification of the real-world
geographic location of an end-user.
Geolocalization Identification of the
real-world geographic location of an the
end-user.
LOCALIZATION THROUGH
location-based GPS
services (LBS): enable
LOCALIZATION THROUGH WI-FI
you to find the
LOCALIZATION devices
THROUGH current
CELLULAR location.
NETWORK

How? You can specify which technology to


use
explicitly by name 2
Maps and location-based services use latitude
and longitude to pinpoint geographic locations,
but your users are more likely to think in terms of
a street address.
The maps library includes a geocoder that you
can use to convert back and forth between
latitude/longitude values and real-world
addresses.
Using the external Maps library included as part of
the Google API package, you can create map-
based Activities using Google Maps as a user
interface element.
You have full access to the map, which enables
you to control display settings, alter the zoom
level, and pan to different locations. 3
Android: Installing Google APIs
EP -1: Install and Setup Google Play Service SDK

Window Android SDK


Manager
Installed packages

Check Google Play


and Google
Repository are
installed,
or install them
http://developer.android.com/google/play- otherwise
services/setup.html

4
Getting a Google Play API Key
Note:Existing keys from a Google Maps Android v1 application,
commonly known as MapView, will not work with the v2 API. The
Google Maps Android API uses a new system of managing keys.
Note:You need anAndroid API key, not a browser key. You can
use the same API key for your Google Maps Android API apps and
yourGoogle Places API for Androidapps.
Access your project's API keys and other credentials as
follows:
1. Go to the Google Developers
Console(https://console.developers.google.com/)
2. In the sidebar on the left, select Credentials.
3. If your project doesn't already have an Android API key,
create one now by selecting Add credentials > API key >
Android key.
4. In the resulting dialog, enter your app's SHA-1 fingerprint
and package name. For ample:
B:0D:AC:74:D3:21:E1:43:67:71:9B:62:91:AF:A1:66:6E:44:5D:75
com.example.android.mapexample 5
Add the API key to your application
Follow the steps below to include the API key in
your application's manifest, contained in the file
AndroidManifest.xml.
In AndroidManifest.xml, add the following element
as a child of the

Substitute your API key for YOUR_API_KEY in the


value attribute. This element sets the key
com.google.android.geo.API_KEY to the value of
your API key.
Save AndroidManifest.xml and re-build your
application.
Note: As shown above, com.google.android.geo.API_KEY is the 6
USING LOCATION-BASED SERVICES
Location-based services is an umbrella term
that describes the different technologies you can
use to find a devices current location.
The two main LBS elements are:
Location Manager - Provides hooks to the location-
based services.
Location Providers -Each of these represents a different
location-fi nding technology used to determine the
devices current location.
Using the Location Manager, you can do the
following:
Obtain your current location
Follow movement
Set proximity alerts for detecting movement into and out
of a specified area
Find available Location Providers 7
Access to the location-based services is provided
by the Location Manager.
To access the Location Manager, request an
instance of the LOCATION_SERVICE using the
getSystemService method, as

Before you can use the location-based services,


you need to add one or more uses-permission tags
to your manifest.
The following snippet shows how to request the fi 8
Fine and coarse permissions-control the level of
accuracy your application can use when
determining the users location,
where fine represents high accuracy and coarse less
so.
Note that an application that has been granted
fine permission will have coarse permission
granted implicitly.

9
SELECTING A LOCATION PROVIDER
Depending on the device, you can use several
technologies to determine the current location.
Each technology, available as a Location
Provider, offers different capabilities including
differences in power consumption, accuracy, and
the ability to determine altitude, speed, or heading
information.
Finding Location Providers
The LocationManager class includes static string
constants that return the provider name for three
Location Providers:
LocationManager.GPS_PROVIDER
LocationManager.NETWORK_PROVIDER
LocationManager.PASSIVE_PROVIDER
The GPS and passive provider requires fine 10
To get a list of the names of all the providers
available (based on hardware available on the
device,and the permissions granted the
application), call getProviders, using a Boolean
to indicate if you want all, or only the enabled,
providers to be returned:

Finding Location Providers by Specifying


Criteria
Use the Criteria class to dictate the requirements
of a provider in terms of accuracy, power use(low,
medium, high), financial cost, and the ability to
return values for altitude, speed, and heading.
Specifies Criteria requiring 11
The coarse/fine values passed in to the
setAccuracy represent a subjective level of
accuracy, where fine represents GPS or better
and coarse any technology signifi cantly less
accurate than that.
additional properties to the Criteria class,
designed for more control over the level of
accuracy you require.
horizontal (latitude/longitude) and medium vertical
(elevation) accuracy are required. 12
In terms of horizontal and vertical accuracy,
high accuracy represents a requirement for results
correct to within 100m.
Low accuracy Providers are correct to more than 500m,
Medium accuracy Providers represent accuracy between
100 and 500 meters.
When specifying accuracy requirements for
bearing and speed, only ACCURACY_LOW and
ACCURACY_HIGH are valid parameters.
Having defined the required Criteria, you can use
getBestProvider to return the best matching Location
Provider or
getProviders to return all the possible matches.

13
getBestProvider to return the best Provider for
If more than one Location Provider matches your
Criteria,

The one with the greatest accuracy is returned.
If no Location Providers meet your
requirements, the Criteria are loosened, in
the following order, until a provide
Power use
Accuracy of returned location
Accuracy of bearing, speed, and altitude
Availability of bearing, speed, and
altitude r is found:
The criterion for allowing a device with monetary
cost is never implicitly relaxed. If no provider is
14
Determining Location Provider Capabilities
To get an instance of a specific provider, call
getProvider, passing in the name:

FINDING YOUR CURRENT LOCATION


Find the physical location of the device. The
accuracy of the returned location is dependent on
the hardware available and the permissions
requested by your application.
Location Privacy
Ensure that your application uses the device
location data in a way that respects the users
privacy by:
Only using and updating location when necessary for
your application 15
Finding the Last Known Location
You can find the last location fix obtained by a
particular Location Provider using the get Last-
Known Location method, passing in the name of
the Location Provider. The following example finds
the last location fix taken by the GPS provider:

getLastKnownLocation does not ask the


Location Provider to update the current
position. If the device has not recently updated
the current position, this value may not exist or be
out of date.
The Location object returned includes all the
position information available from the provider
that supplied it. This can include 16
Where Am I Example
finds the devices last known location using the
GPS Location Provider.
This example assumes that
you have enabled the GPS_PROVIDER Location Provider
using the techniques or that youre running it on a device
that supports GPS and has that hardware enabled.
In order to work, the device or Emulator must have
recorded at least one location update. In the case of a
device, this is most easily achieved by starting the Google
Maps application; on an Emulator, enable location
updates as described
1. Create a new Where Am I project with a
WhereAmI Activity. This example uses the GPS
provider,
2. so you need to include the uses-permission tag
for ACCESS_FINE_LOCATION in your application 17
18
3. Modify the main.xml layout resource to include an
android:ID attribute for the TextView control so
that you can access it from within the Activity.

19
Override the onCreate method of the WhereAmI Activity to get a
reference to the Location Manager.
Define LocationManager and Provider Class
Call getLastKnownLocation to get the last known location, and
pass it in to an updateWithNewLocation method stub.

20
Complete the updateWithNewLocation method
to show the passed-in Location in the Text View by
extracting the latitude and longitude values.

21
Refreshing the Current Location
The requestLocationUpdates methods are used
to request regular updates of location changes
using a LocationListener.
Location Listeners also contain hooks for
changes in a providers status and availability.
The requestLocationUpdates method accepts
either a specific Location Provider name or a
set of Criteria to determine the provider to use.
To optimize efficiency and minimize cost and
power use, you can also specify the minimum
time and the minimum distance between
location change updates.
Example: shows the skeleton code for requesting
regular updates based on a minimum time and
distance using a Location Listener. 22
23
Tracking Your Location in Where Am I
In this example, the Where Am I project is
enhanced to update your current location by
listening for location changes.
Updates are restricted to one every 2 seconds,
and only when movement of more than 10
meters has been detected.
Rather than explicitly selecting a provider, you
update the application to use a set of Criteria and
let Android find the best provider available.
1. Open the WhereAmI Activity
Update the onCreate method to use Criteria to find a
Location Provider that features high accuracy and
draws as little power as possible.

24
Requesting a Single Location Update

25
Create a new LocationListener instance variable
that fires the existing updateWithNew Location
method whenever a location change is detected.

26
BEST PRACTICE FOR LOCATION UPDATES

When using Location within your application,


consider the following factors:
Battery life versus accuracy - The more
accurate the Location Provider, the greater its
drain on the battery.
Startup time - In a mobile environment the time
taken to get an initial location can have a dramatic
effect on the user experience particularly if your
app requires a location to be used. GPS, for
example, can have a significant startup time,
which you may need to mitigate.
Update rate - The more frequent the update rate,
the more dramatic the effect on battery life.
Slower updates can reduce battery drain at the
price of less timely updates. 27
USING THE GEOCODER
Geocoding enables you to translate between street
addresses and longitude/latitude map coordinates.
This can give you a recognizable context for the locations
and coordinates used in location based services and
map-based Activities.
The Geocoder classes are included as part of the Google
Maps library, so to use them you need to import it into your
application by adding a uses-library node within the
application node as shown here:
<uses-library
android:name=com.google.android.maps/>
As the geocoding lookups are done on the server, your
applications also requires the Internet uses permission in
your manifest:
<uses-permission
android:name=android.permission.INTERNET/>
The Geocoder class provides access to two geocoding
functions: 28
The results from these calls are contextualized by
means of a locale (used to define your usual
location and language).
The following snippet shows how you set the locale
when creating your Geocoder. If you dont specify
a locale, it assumes the devices default.
Geocoder geocoder = new
Geocoder(getApplicationContext(), Locale.getDefault());
Both geocoding functions return a list of Address
objects. Each list can contain several possible
results, up to a limit you specify when making the
call.
The Geocoder uses a web service to implement
its lookups that may not be included on all Android
devices. Android 2.3 (API level 9) introduced the 29
Reverse Geocoding
Reverse geocoding returns street addresses for
physical locations specified by latitude/longitude
pairs. Its a useful way to get a recognizable
context for the locations returned by location-
based services.
To perform a reverse lookup, pass the target
latitude and longitude to a Geocoder objects
getFrom-Location method. It returns a list of
possible address matches.
If the Geocoder could not resolve any addresses
for the specified coordinate, it returns null.

30
Forward Geocoding
Forward geocoding (or just geocoding) determines
map coordinates for a given location.
To geocode an address, call
getFromLocationName on a Geocoder object.
Pass in a string that describes the address you
want the coordinates for, the maximum number of
results to return, and optionally provide a
geographic bounding box within which to restrict
your search results:
List<Address> result =
gc.getFromLocationName(streetAddress,
maxResults);
As with reverse geocoding, if no matches are
found, null is returned. The availability,accuracy,
and granularity of geocoding results depends 31
Geocoding Where Am I
In this example you extend the Where Am I project
to include and update the current street address
whenever the device moves.

32
33
34
CREATING MAP-BASED ACTIVITIES
One of the most intuitive ways to provide context
for a physical location or address is to use a map.
Using a MapView, you can create Activities that
include an interactive map.
Map Views support annotation using Overlays and
by pinning Views to geographical locations.
Map Views offer full programmatic control of the
map display, letting you control the zoom,
location, and display modes including the option
to display a satellite view.
In the following sections you see
how to use Overlays and the MapController to create
dynamic map-based Activities.
Unlike online mashups, your map Activities run
natively on the device, giving you a more 35
Introducing Map View and Map Activity
This section introduces several classes used to
support Android maps:
MapView: is the user interface element that
displays the map.
MapActivity: is the base class you extend to
create an Activity that can include a Map View. The
MapActivity class handles the application life cycle
and background service management required for
displaying maps. You can only use Map Views
within MapActivity-derived Activities.
Overlay: is the class used to annotate your maps.
Using Overlays, you can use a Canvas to draw
onto any number of layers displayed on top of a
Map View.
MapController: is used to control the map, 36
Getting Your Maps API Key
To use a Map View in your application, you must
first obtain an API key from the Android developer
website at http://code.google.com/android/maps-
api-signup.html.
Without an API key the Map View cannot download
the tiles used to display the map.
To obtain a key, you need to specify the MD5
fingerprint of the certificate used to sign your
application.
Generally, you sign your application using two
certificates: a default debug certificate and a
production certificate.
The following sections explain how to obtain the
MD5 fingerprint of any signing certificate used
with your application. 37
Creating a Map-Based Activity
To use maps in your applications, you need to
extend MapActivity.
The layout for the new class must then include a
MapView to display a Google Maps interface
element.
Override the onCreate method to lay out the
screen that includes a MapView, and
override isRouteDisplayed to return true if the
Activity will be displaying routing information (such
as traffic directions).
The Android maps library is not a standard Android
package; as an optional API, it must be explicitly
included in the application manifest before it can
be used. Add the library to your manifest
<uses-library 38
MyMapActivity

39
MapView.xml

Android currently supports only one MapActivity and one


MapView per
application.
40
Configuring and Using Map Views
By default the Map View shows the standard street
In addition display a satellite view and the
expected traffic overlay, as shown in the following
code snippet:
mapView.setSatellite(true);
mapView.setTraffic(true);
You can also query the Map View to find the
current and maximum available zoom levels:
int maxZoom = mapView.getMaxZoomLevel();
int currentZoom = mapView.getZoomLevel();
You can also obtain the center point and currently
visible longitude and latitude span (in decimal
degrees). This is particularly useful for performing
geographically limited Geocoder lookups:
GeoPoint center = mapView.getMapCenter(); 41
You can also choose to display the standard map
zoom controls using the setBuiltInZoomControls
method.
mapView.setBuiltInZoomControls(true);
To customize the zoom controls use the method to
obtain an instance getZoomButtonsController of
the Zoom Buttons Controller.
You can use the controller to customize the zoom
speed, enable or
disable the zoom in or out controls, and add
additional buttons to the zoom controls layout.
ZoomButtonsController zoomButtons =
MapView.getZoomButtonsController();

42
Using the Map Controller
Use the Map Controller to pan and zoom a MapView. You can
get a reference to a MapViews controller using getController.
MapController mapController = mapView.getController();
Map locations in the Android mapping classes are
represented by GeoPoint objects, which contain a latitude
and longitude measured in microdegrees. To convert
degrees to microdegrees, multiply by 1E6 (1,000,000).
Before you can use the latitude and longitude values stored
in the Location objects returned by location-based services,
you need to convert them to microdegrees and store them
as GeoPoints.
Double lat = 37.422006*1E6;
Double lng = -122.084095*1E6;
GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue());
Recenter and zoom the Map View using the setCenter and
setZoom methods available on the Map Views
MapController.
43
mapController.setCenter(point);
Mapping Where Am I
The following code example extends the Where Am I project
again. This time you add mapping functionality by
transforming it into a Map Activity. As the device location
changes, the map automatically re-centers on the new
position.
1. Start by checking your project properties to ensure your
project build target is a Google APIs target rather than an
Android Open Source Project target
2. Modify the application manifest t to add the maps library:

3. Change the inheritance of the WhereAmI Activity to


extend MapActivity instead of Activity. You also need to
include an override for the isRouteDisplayed method.
Because this Activity wont show routing directions, you can
44
return false.
4. Modify the main.xml layout resource to include a MapView
using the fully qualifi ed class name. You need to obtain a
maps API key to include within the android:apikey attribute
of the com.android.MapView node.

45
5. Running the application now should display the
original address text with a MapView beneath it, as
shown in Figure below.

46
6. Returning to the WhereAmI Activity, configure the Map View and
store a reference to its MapController as an instance variable. Set
up the Map View display options to show the satellite and zoom in
for a closer look.

47
7. The final step is to modify the updateWithNewLocation
method to re-center the map on the current location using
the Map Controller:

48
49
Reading Assignment
Creating and Using Overlays
Creating New Overlays
Drawing on the Overlay Canvas
Handling Map Tap Events
Adding and Removing Overlays

50

You might also like