Location Services: Part 1 (Location and Geocoding)

Slides:



Advertisements
Similar presentations
Android Application Development Tutorial. Topics Lecture 4 Overview Overview of Sensors Programming Tutorial 1: Tracking location with GPS and Google.
Advertisements

CIMCO Integration Software Products
The Android Activity Lifecycle. Slide 2 Introduction Working with the Android logging system Rotation and multiple layouts Understanding the Android activity.
Tracking & Login Data persistence User tracking.
CS378 - Mobile Computing Maps. Using Google Maps Like other web services requires an API key from Google ons/google-apis/mapkey.html.
Location-Based Services: Part 2 (Google Maps)
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
Location & Maps.  Mobile applications can benefit from being location-aware, e.g.,  Routing from a current to a desired location  Searching for stores.
Debugging Android Applications
Location and Maps Content Getting Location Getting Google Map In application Test on Emulator/Device.
ANDROID PROGRAMMING MODULE 1 – GETTING STARTED
CS378 - Mobile Computing Location.
CS378 - Mobile Computing Maps. Using Google Maps Content on using Google Maps inside your app Alternatives: Open Street Maps –
Data Storage: Part 1 (Preferences)
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
Android Sensors & Async Callbacks Jules White Bradley Dept. of Electrical and Computer Engineering Virginia Tech
Route Tracker App Android How to Program © by Pearson Education, Inc. All Rights Reserved.
Mobile Programming Lecture 1 Getting Started. Today's Agenda About the Eclipse IDE Hello, World! Project Android Project Structure Intro to Activities,
Google Maps Android API v2 吳俊興 國立高雄大學 資訊工程學系 CSF645 – Mobile Computing 行動計算
Location-Based API 1. 2 Location-Based Services or LBS allow software to obtain the phone's current location. This includes location obtained from the.
© Keren Kalif Intro to Android Development Written by Keren Kalif, Edited by Liron Blecher Contains slides from Google I/O presentation.
Location based services Using Google Maps v2 etc. in Android apps 1Location based services.
XP New Perspectives on Microsoft Office Access 2003 Tutorial 12 1 Microsoft Office Access 2003 Tutorial 12 – Managing and Securing a Database.
Location based services
CSS216 MOBILE PROGRAMMING Android, Chapter 8 Book: “Professional Android™ 2 Application Development” by Reto Meier, 2010 by: Andrey Bogdanchikov (
Networking: Part 2 (Accessing the Internet). The UI Thread When an application is launched, the system creates a “main” UI thread responsible for handling.
ANDROID Presented By Mastan Vali.SK. © artesis 2008 | 2 1. Introduction 2. Platform 3. Software development 4. Advantages Main topics.
Data Storage: Part 4 (Content Providers). Content Providers Content providers allow the sharing of data between applications. Inter-process communication.
Android Accessing GPS Ken Nguyen Clayton State University 2012.
9 Chapter Nine Compiled Web Server Programs. 9 Chapter Objectives Learn about Common Gateway Interface (CGI) Create CGI programs that generate dynamic.
1 CMSC 628: Introduction to Mobile Computing Nilanjan Banerjee Introduction to Mobile Computing University of Maryland Baltimore County
© 2016 Cengage Learning®. May not be scanned, copied or duplicated, or posted to a publicly accessible website, in whole or in part. Android Boot Camp.
Android Programming-Activity Lecture 4. Activity Inside java folder Public class MainActivity extends ActionBarActivity(Ctrl + Click will give you the.
Overview of Android Application Development
Services A Service is an application component that can perform long-running operations in the background and does not provide a user interface. An application.
MAKANI ANDROID APPLICATION Prepared by: Asma’ Hamayel Alaa Shaheen.
GPS Provider:  GPS signal Network Location Provider:  Cell ID  Wi-Fi.
Location. GPS Global Positioning System – At least 4 satellites typically used 3 required extra for error detection and altitude typically accurate within.
Maps Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution 2.5 License.
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
Android - Location Based Services. Google Play services facilitates adding location awareness to your app with automated location tracking Geo fencing.
ANDROID APPLICATION DEVELOPMENT. ANDROID DEVELOPMENT DEVELOPER.ANDROID.COM/INDEX.HTML THE OFFICIAL SITE FOR ANDROID DEVELOPERS. PROVIDES THE ANDROID SDK.
Manual Testing Lesson 3 Test Driving your application.
TCS Internal Maps. 2 TCS Internal Objective Objective :  MAPS o Integration of Maps.
Intoduction to Andriod studio Environment With a hello world program.
Cosc 5/4735 YouTube API. YouTube The YouTube Android Player API enables you to incorporate video playback functionality into your Android applications.
Cosc 4735 LocationAware API. Previous on … Before we looked at GPS location. – d-gpslocation.pptx
Location Based Services. Android location APIs make it easy for you to build location-aware applications, without needing to focus on the details of the.
Lecture 5: Location Topics: Google Play Services, Location API Date: Feb 16, 2016.
School of Engineering and Information and Communication Technology KIT305/KIT607 Mobile Application Development Android OS –Permissions (cont.), Fragments,
CS371m - Mobile Computing Maps. Using Google Maps Content on using Google Maps inside your app Alternatives Exist: – Open Street Maps –
1. 2 Android location services Determining a device’s current location Tracking device movements Proximity alerts.
CS499 – Mobile Application Development Fall 2013 Location & Maps.
Introduction to Android Programming
Lecture 5: Location Topics: Google Play Services, Location API
Location Services: Part 1 (Location and Geocoding)
Android Application -Architecture.
Android Application Maps 1.
Lecture 5: Location Topics: Google Play Services, Location API.
Location-Based Services: Part 2 (Google Maps)
Android Studio, Android System Basics and Git
Activities and Intents
Android Location Based Services
Android 20: Location Kirk Scott.
Sensors, maps and fragments:
CIS 470 Mobile App Development
Lecture 5: Location Topics: Google Play Services, Location API.
Mobile Programming Dr. Mohsin Ali Memon.
CS378 - Mobile Computing Location and Maps.
Maps, Geocoding, and Location-Based Services.
Presentation transcript:

Location Services: Part 1 (Location and Geocoding)

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

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

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

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.

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

Setting Up Google Play Services ( 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

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).

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

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

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 protected void onCreate(Bundle savedInstanceState) {... buildGoogleApiClient();... } Slide 11©SoftMoore Consulting (continued on next page)

Example: Connecting to Google Play Services (continued) protected synchronized void buildGoogleApiClient() { googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); public void onConnected(Bundle connectionHint) { // Provides a simple way of getting a device's location } Slide 12©SoftMoore Consulting (continued on next page)

Example: Connecting to Google Play Services 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(); 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)

Example: Connecting to Google Play Services protected void onStart() { super.onStart(); googleApiClient.connect(); protected void onStop() { super.onStop(); if (googleApiClient.isConnected()) googleApiClient.disconnect(); }... Slide 14©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 or higher Slide 15©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 <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.

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

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

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

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

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, Bundle getExtras() –Returns additional provider-specific information about the location fix as a Bundle. Slide 21©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©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©SoftMoore Consulting (continued on next page)

Example: Obtaining the Last Known Location 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

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.

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.

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

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

Example: Receiving Location Updates public class MainActivity extends ActionBarActivity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener { protected GoogleApiClient googleApiClient; protected LocationRequest locationRequest; protected Location 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)

Example: Receiving Location Updates 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)

Example: Receiving Location Updates public void onLocationChanged(Location location) { currentLocation = location; updateUI(); public void onResume() { super.onResume(); if (googleApiClient.isConnected()) startLocationUpdates(); }... // other lifecycle methods Slide 31©SoftMoore Consulting LocationListener callback method

Example: Using LocationListener (continued) Slide 32©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 Slide 33©SoftMoore Consulting

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

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 –KML Tutorial Slide 35©SoftMoore Consulting

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 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.

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

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

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)

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

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

Example: Geocoding Slide 42©SoftMoore Consulting

Relevant Links Location APIs Setting Up Google Play Services Getting the Last Known Location Receiving Location Updates Displaying a Location Address Slide 43©SoftMoore Consulting