location services: part 1 (location and geocoding)

43
Location Services: Part 1 (Location and Geocoding)

Upload: rosa-harmon

Post on 27-Dec-2015

231 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Location Services: Part 1 (Location and Geocoding)

Location Services: Part 1(Location and Geocoding)

Page 2: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Overview of Location-Based Services

• Location-based services use real-time location data from a mobile device or smartphone to provide information, entertainment, or security.

• Location-Based services are available on most smartphones, and a majority of smartphone owners use location-based services.

• Many popular applications integrate location-based services. Examples include– GasBuddy − TripAdvisor– IMDb − Google Maps– Starbucks − The Weather Channel– Navigation − Facebook Places

Slide 2

Page 3: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Location Providers

• GPS is more accurate, but– it only works outdoors– it quickly consumes battery power– it doesn't return the location quickly

• Android’s Network Location Provider determines user location using cell towers and Wi-Fi signals. It is less accurate than GPS, but– it works indoors and outdoors– it responds faster– it and uses less battery power

Slide 3

Page 4: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Challenges in Determining User Location

• Multitude of location sourcesGPS, Cell-ID, and Wi-Fi can each provide a clue to users location. Determining which to use and trust is a matter of trade-offs in accuracy, speed, and battery-efficiency.

• User movementBecause the user location changes, you must account for movement by re-estimating user location every so often.

• Varying accuracyLocation estimates from each location source are not consistent in their accuracy. A location obtained 10 seconds ago from one source might be more accurate than the newest location from another or same source.

Slide 4

Page 5: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Location-Based Services in Android

• Android provides two location frameworks– in package android.location– in package com.google.android.gms.location

(part of Google Play services)

• The framework provided by Google Play services is now the preferred way to add location-based services to an application.– simpler API − greater accuracy– more power efficient − more versatile

Slide 5

Note that some classes in package android.locationare still used by the Google Play services API.

Page 6: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Download Google Play Services(Android SDK Manager)

Slide 6

Page 7: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Setting Up Google Play Services(https://developer.android.com/google/play-services/setup.html)

• Make sure that the Google Play services SDK is installed, as shown in the previous slide.

• Create an application using Android Studio.

• In Android Studio under “Gradle Scripts”, edit the build.gradle file for “Module: app”(not the build.gradle file for the project)

Under dependencies (near the bottom), add the following line at the end:compile 'com.google.android.gms:play-services-

location:6.5.+'

• Save the changes and click “Sync Project with Gradle Files” in the toolbar, or click on menu itemTools Android Sync Project with Gradle Files.

Slide 7

Page 8: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Setting Up Google Play Services(continued)

• Edit file AndroidManifest.xml and add the following tag as a child of the <application> element:<meta-data android:name="com.google.android.gms.version"       android:value="@integer/google_play_services_version"/>

Slide 8

Note: You can ignore instructions about creating a ProGuardexception if you are building in debug mode (i.e., not release mode).

Page 9: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Key Interfaces for Google Play Services(in package

com.google.android.gms.common.api)

• GoogleApiClient– main entry point for Google Play services integration

• GoogleApiClient.ConnectionCallbacks– provides callbacks that are called when the client is connected or

disconnected from the service– abstract methods:

void onConnected(Bundle connectionHint)void onConnectionSuspended(int cause)

• GoogleApiClient.OnConnectionFailedListener– provides callbacks for scenarios that result in a failed attempt to

connect the client to the service– abstract method:

void onConnectionFailed(ConnectionResult result)

Slide 9

Page 10: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Steps in Connecting to Google Play Services

• Import classes/interfaces.

• Declare that the activity implements callback interfaces.

• Declare/build GoogleApiClient object.

• Implement callback interfaces.

• Implement methods onStart() and onStop() (and possibly other lifecycle methods such as onPause()and onResume()) to gracefully handle connections to Google Play Services

Slide 10

Page 11: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Connecting to Google Play Services

import com.google.android.gms.common.ConnectionResult;import com.google.android.gms.common.api.GoogleApiClient;import com.google. ... GoogleApiClient.ConnectionCallbacks;import com.google. ... GoogleApiClient.OnConnectionFailedListener;...

public class MainActivity extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener { protected GoogleApiClient googleApiClient; ...

@Override protected void onCreate(Bundle savedInstanceState) { ... buildGoogleApiClient(); ... }

Slide 11

(continued on next page)

Page 12: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Connecting to Google Play Services(continued)

protected synchronized void buildGoogleApiClient() { googleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); }

@Override public void onConnected(Bundle connectionHint) { // Provides a simple way of getting a device's location }

Slide 12

(continued on next page)

Page 13: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Connecting to Google Play Services(continued)

@Override public void onConnectionSuspended(int cause) { // The connection to Google Play services was lost. // Attempt to re-establish the connection. Log.i(LOG_TAG, "Connection suspended"); googleApiClient.connect(); }

@Override public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult // for possible error codes. Log.i(LOG_TAG, "Connection failed: error code = " + result.getErrorCode()); }

Slide 13

(continued on next page)

Page 14: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Connecting to Google Play Services(continued)

@Override protected void onStart() { super.onStart(); googleApiClient.connect(); }

@Override protected void onStop() { super.onStop(); if (googleApiClient.isConnected()) googleApiClient.disconnect(); }

...

Slide 14

Page 15: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Testing Google Play Services

To test an application using the Google Play services SDK, you must use either

• A compatible Android device that runs Android 2.3 or higher and includes Google Play Store

• An Android emulator (virtual device) that runs the Google APIs platform based on Android 4.2.2 or higher

Slide 15

Page 16: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Requesting User Permissions

• In order to receive location updates, user permission must be requested in the Android manifest file.– ACCESS_COARSE_LOCATION to access locations provided by

cell tower/Wi-Fi triangulation– ACCESS_FINE_LOCATION to access locations provided by GPS

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

Slide 16

Note: The ACCESS_FINE_LOCATION permissionincludes permission for both location providers.

Page 17: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

The Fused Location Provider

• The location APIs in Google Play services contains a fused location provider

• The fused location provider manages the underlying location technology and provides a simple API that– allows you to specify requirements at a high level, like high

accuracy or low power– optimizes the device’s use of battery power

Slide 17

Page 18: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Key Location Classes and Interfaces

In package android.location

• Class Location– represents a geographic location sensed at a particular time

• Class Address– represents an address as a set of strings describing a location.

• Class Geocoder– translates between locations and addresses

Slide 18

Page 19: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Key Location Classes and Interfaces(continued)

In package com.google.android.gms.location

• Class LocationServices– main entry point for location services integration

• Interface FusedLocationProviderApi– main entry point for interacting with the fused location provider

• Interface LocationListener– receives notifications when the location has changed

• Class LocationRequest– contains quality-of-service parameters for requests to the FusedLocationProviderApi

Slide 19

Page 20: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Class Location

• A location consists of– a latitude– a longitude– a UTC timestamp

• A location can optionally contain information on altitude, speed, and bearing.

• Information specific to a particular provider or class of providers may be communicated to the application using method getExtras(), which returns a Bundle of key/value pairs. Each provider will only provide those entries for which information is available.

Slide 20

Page 21: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Selected Methods in Class Location

• double getLatitude()– Returns the latitude of this fix.

• double getLongitude()– Returns the longitude of this fix.

• double getAltitude()– Returns the altitude if available, in meters.

• long getTime()– Returns the UTC time of this fix in milliseconds since January 1,

1970.

• Bundle getExtras()– Returns additional provider-specific information about the

location fix as a Bundle.

Slide 21

Page 22: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Obtaining the Last Known Location

• Class LocationServices contains a static reference to a FusedLocationProviderApi object named LocationServices.FusedLocationApi

• Using this object, call getLastLocation(GoogleApiClient client)to obtain the best and most recent location currently available.

Slide 22

Page 23: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Obtaining the Last Known Location

public class MainActivity extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener { ... protected Location lastLocation;

protected TextView latitudeTextView; protected TextView longitudeTextView; ...

Slide 23

(continued on next page)

Page 24: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Obtaining the Last Known Location(continued)

@Overridepublic void onConnected(Bundle connectionHint) { FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi; lastLocation = locationProvider.getLastLocation(googleApiClient); if (lastLocation != null) { String latStr = Double.toString(lastLocation.getLatitude()); String longStr = Double.toString(lastLocation.getLongitude()); latitudeTextView.setText(latStr); longitudeTextView.setText(longStr); } ... }

Slide 24

Page 25: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Obtaining the Last Known Location

Slide 25

Last location

Address of this location(obtained using geocoding, which will be discussed insubsequent slides.

Page 26: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Interface LocationListener

• Interface LocationListener is used for receiving notifications from the FusedLocationProvider when the location has changed.

• The interface specifies one abstract callback method that is called when the location changes.void onLocationChanged(Location location)

Slide 26

Note that there are two Android interfaces namedLocationListener, one in package android.location,and one that is part of Google Play Services in packagecom.google.android.gms.location. This sectionrefers to the interface defined in Google Play Services.

Page 27: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Receiving Location Updates

• Connect to Google Play services as described earlier in this section.

• Set up a location request specifying quality-of-service parameters for the FusedLocationProviderApi. Examples include– priority (accuracy versus power)– desired interval for updates

• Implement the LocationListener callback.

• Request location updates– usually part of the onConnected() method

Slide 27

Page 28: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Set Up LocationRequest

private static final int INTERVAL = 10000; // 10 secondsprivate static final int FASTEST_INTERVAL = 5000; // 5 seconds

protected void createLocationRequest() {    locationRequest = new LocationRequest();

// Set desired interval for location updates (inexact)    locationRequest.setInterval(INTERVAL);

// Explicitly set the fastest interval for location updates    locationRequest.setFastestInterval(FASTEST_INTERVAL);

// request the most accurate locations available    locationRequest.setPriority( LocationRequest.PRIORITY_HIGH_ACCURACY); } Slide 28

Page 29: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Receiving Location Updates

public class MainActivity extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener { protected GoogleApiClient googleApiClient; protected LocationRequest locationRequest; protected Location currentLocation; ...

@Override public void onCreate(Bundle savedInstanceState) { ... buildGoogleApiClient(); createLocationRequest(); }

Slide 29

initialized to lastlocation as describedearlier in this section

(continued on next page)

Page 30: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Receiving Location Updates(continued)

@Override public void onConnected(Bundle connectionHint) { ... // initialize currentLocation using last // location as described earlier

updateUI(); startLocationUpdates(); }

protected void startLocationUpdates() { FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi; locationProvider.requestLocationUpdates(googleApiClient, locationRequest, this); }

Slide 30

(continued on next page)

Page 31: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Receiving Location Updates(continued)

@Override public void onLocationChanged(Location location) { currentLocation = location; updateUI(); }

@Override public void onResume() { super.onResume(); if (googleApiClient.isConnected()) startLocationUpdates(); }

... // other lifecycle methods

Slide 31

LocationListenercallback method

Page 32: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Using LocationListener(continued)

Slide 32

Page 33: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Location Services on the Emulator

• A virtual device (emulator) does not have GPS or real location providers, so it uses a “mock” GPS provider that always returns the same position unless it is changed manually.

• The location on the emulator can be changed using– the Android Device Monitor– the “geo” command in the emulator console; e.g.,geo fix -79.960138 32.797917

Slide 33

Page 34: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Setting a Mock Location on an EmulatorUsing the Android Device Monitor

Slide 34

Emulator Control Panel

Page 35: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Using the Emulator Control Panel

• The Emulator Control panel can send simulated location data in three different ways:– Manually send individual longitude/latitude coordinates to the

device.– Use a GPX file describing a route for playback to the device.– Use a KML file describing individual place marks for sequenced

playback to the device.

• See the following for details of GPX and KML files:– GPX: The GPS Exchange Format

http://www.topografix.com/gpx.asp – KML Tutorial

http://code.google.com/apis/kml/documentation/kml_tut.html

Slide 35

Page 36: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Setting a Mock LocationUsing the “geo” Command

To send mock location data from the command line:

• In Android Studio, click on the “Terminal” tab near the bottom.

• Connect to the emulator console: telnet localhost 5554

• Send the location data: geo fix -121.45356 46.51119 4392

Slide 36

5554 is the console port(check emulator screen)

Note that a telnet client is not installed automatically in Window. UseControl Panel Programs and Features Turn Windows features on or off

The “geo fix” command accepts a longitude and latitudein decimal degrees, and an optional altitude in meters.

Page 37: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Geocoding

• Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate.

• Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address.

Slide 37

Page 38: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Class Geocoder

• Class Geocoder (in package android.location) handles geocoding and reverse geocoding.

• The Geocoder class requires a backend service that is not included in the core android framework.– may not work on the emulator

• The Geocoder query methods will return an empty list if there no backend service in the platform.

• Use the isPresent() method to determine whether a Geocoder implementation exists.

Slide 38

Page 39: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Translating a Location to an Address(Reverse Geocoding)

private Address getAddress(Location location) { Address address = null;

try { Geocoder geocoder = new Geocoder(this); double latitude = location.getLatitude(); double longitude = location.getLongitude(); int maxResults = 1; List<Address> addresses = geocoder.getFromLocation (latitude, longitude, maxResults);

if (addresses.size() > 0) address = addresses.get(0); }

Slide 39

(continued on next page)

Page 40: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Translating a Location to an Address(continued)

catch (IOException ex) { Log.e(LOG_TAG, ex.getMessage()); }

return address; }

Slide 40

Page 41: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Translating an Address to a Location(Geocoding)

• Create a string with the addressString addressStr = "171 Moultrie Street, Charleston, SC, 29409";

• Create a Geocoder instanceGeocoder geocoder = new Geocoder(this);

• Call the Geocoder method getFromLocationName()List<Address> addresses = geocoder.getFromLocationName(addressStr, 1);

• Retrieve the latitude and longitude from the first addressAddress address = addresses.get(0);// call address.getLatitude() and// address.getLongitude() as needed

Slide 41

Page 42: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Example: Geocoding

Slide 42

Page 43: Location Services: Part 1 (Location and Geocoding)

©SoftMoore Consulting

Relevant Links

• Location APIshttps://developer.android.com/google/play-services/location.html

• Setting Up Google Play Serviceshttps://developer.android.com/google/play-services/setup.html

• Getting the Last Known Locationhttp://developer.android.com/training/location/retrieve-current.html

• Receiving Location Updateshttp://developer.android.com/training/location/receive-location-updates.html

• Displaying a Location Addresshttp://developer.android.com/training/location/display-address.html

Slide 43