Presentation is loading. Please wait.

Presentation is loading. Please wait.

Location Services: Part 1 (Location and Geocoding)

Similar presentations


Presentation on theme: "Location Services: Part 1 (Location and Geocoding)"— Presentation transcript:

1 Location Services: Part 1 (Location and Geocoding)

2 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©SoftMoore Consulting

3 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©SoftMoore Consulting

4 Challenges in Determining User Location Multitude of location sources GPS, 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 movement Because the user location changes, you must account for movement by re-estimating user location every so often. Varying accuracy Location 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©SoftMoore Consulting

5 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©SoftMoore Consulting Note that some classes in package android.location are still used by the Google Play services API.

6 Download Google Play Services (Android SDK Manager) Slide 6©SoftMoore Consulting

7 Setting Up Google Play Services (https://developer.android.com/google/play-services/setup.html)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 item Tools  Android  Sync Project with Gradle Files. Slide 7©SoftMoore Consulting

8 Setting Up Google Play Services (continued) Edit file AndroidManifest.xml and add the following tag as a child of the element: Slide 8©SoftMoore Consulting Note: You can ignore instructions about creating a ProGuard exception if you are building in debug mode (i.e., not release mode).

9 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©SoftMoore Consulting

10 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©SoftMoore Consulting

11 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©SoftMoore Consulting (continued on next page)

12 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©SoftMoore Consulting (continued on next page)

13 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©SoftMoore Consulting (continued on next page)

14 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©SoftMoore Consulting

15 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©SoftMoore Consulting

16 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 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>... Slide 16©SoftMoore Consulting Note: The ACCESS_FINE_LOCATION permission includes permission for both location providers.

17 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©SoftMoore Consulting

18 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©SoftMoore Consulting

19 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©SoftMoore Consulting

20 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©SoftMoore Consulting

21 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©SoftMoore Consulting

22 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©SoftMoore Consulting

23 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©SoftMoore Consulting (continued on next page)

24 Example: Obtaining the Last Known Location (continued) @Override public 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©SoftMoore Consulting

25 Obtaining the Last Known Location Slide 25©SoftMoore Consulting Last location Address of this location (obtained using geocoding, which will be discussed in subsequent slides.

26 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©SoftMoore Consulting Note that there are two Android interfaces named LocationListener, one in package android.location, and one that is part of Google Play Services in package com.google.android.gms.location. This section refers to the interface defined in Google Play Services.

27 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©SoftMoore Consulting

28 Example: Set Up LocationRequest private static final int INTERVAL = 10000; // 10 seconds private 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©SoftMoore Consulting

29 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©SoftMoore Consulting initialized to last location as described earlier in this section (continued on next page)

30 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©SoftMoore Consulting (continued on next page)

31 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©SoftMoore Consulting LocationListener callback method

32 Example: Using LocationListener (continued) Slide 32©SoftMoore Consulting

33 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©SoftMoore Consulting

34 Setting a Mock Location on an Emulator Using the Android Device Monitor Slide 34©SoftMoore Consulting Emulator Control Panel

35 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 http://www.topografix.com/gpx.asp –KML Tutorial http://code.google.com/apis/kml/documentation/kml_tut.html http://code.google.com/apis/kml/documentation/kml_tut.html Slide 35©SoftMoore Consulting

36 Setting a Mock Location Using 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©SoftMoore Consulting 5554 is the console port (check emulator screen) Note that a telnet client is not installed automatically in Window. Use Control Panel  Programs and Features  Turn Windows features on or off The “geo fix” command accepts a longitude and latitude in decimal degrees, and an optional altitude in meters.

37 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©SoftMoore Consulting

38 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©SoftMoore Consulting

39 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 addresses = geocoder.getFromLocation (latitude, longitude, maxResults); if (addresses.size() > 0) address = addresses.get(0); } Slide 39©SoftMoore Consulting (continued on next page)

40 Example: Translating a Location to an Address (continued) catch (IOException ex) { Log.e(LOG_TAG, ex.getMessage()); } return address; } Slide 40©SoftMoore Consulting

41 Translating an Address to a Location (Geocoding) Create a string with the address String addressStr = "171 Moultrie Street, Charleston, SC, 29409"; Create a Geocoder instance Geocoder geocoder = new Geocoder(this); Call the Geocoder method getFromLocationName() List addresses = geocoder.getFromLocationName(addressStr, 1); Retrieve the latitude and longitude from the first address Address address = addresses.get(0); // call address.getLatitude() and // address.getLongitude() as needed Slide 41©SoftMoore Consulting

42 Example: Geocoding Slide 42©SoftMoore Consulting

43 Relevant Links Location APIs https://developer.android.com/google/play-services/location.html Setting Up Google Play Services https://developer.android.com/google/play-services/setup.html Getting the Last Known Location http://developer.android.com/training/location/retrieve-current.html Receiving Location Updates http://developer.android.com/training/location/receive-location-updates.html Displaying a Location Address http://developer.android.com/training/location/display-address.html Slide 43©SoftMoore Consulting


Download ppt "Location Services: Part 1 (Location and Geocoding)"

Similar presentations


Ads by Google