- Overview
- Introduction
- Concepts
- API overview
- Policies and Terms
- Android Developer’s Guide to the Google Location Services API
- Package “android.location”
- Google Location Services API
- Requesting Permission, Configuring AndroidManifest.xml
- Checking for Google Play Services Availability
- Accessing Google APIs
- Listening for Location Updates
- Stop Listening for Updates
- Wrapping Up
- Location
- In this document
- Related samples
- Adding the required permission
- Creating the driver
- Reporting location
- Converting GPS data
Overview
Introduction
The Places SDK for Android allows you to build location-aware apps that respond contextually to the local businesses and other places near the user’s device. This means you can build rich apps based on places that mean something to the user, to complement the straightforward geographic-based services offered by the Android location services.
Concepts
The following interfaces provide the primary entry points to the Places SDK for Android:
- Places provides programmatic access to Google’s database of local place and business information, as well as the device’s current place.
- Autocomplete provides pre-made widgets to return place predictions in response to user search queries.
A place is defined as a physical space that has a name. Another way of thinking about a place is that it’s anything you can find on a map. Examples include local businesses, points of interest, and geographic locations. In the API, a place is represented by the Place interface. It includes information such as the name of the place and its address, geographical location, place ID, phone number, place type, website URL, and more.
API overview
Help your customers explore where they are and what’s around them:
- Place Autocomplete automatically fills in the name and/or address of a place as users type.
- Current Place returns a list of places where the user’s device is last known to be located along with an indication of the relative likelihood for each place.
- Place Details return and display more detailed information about a place.
- Place Photos returns high-quality images of a place.
- Place IDs stores the unique ID for one or more places for retrieval of place information on demand.
Note: Google gathers anonymous usage statistics.
Policies and Terms
All applications that use the Places SDK for Android must adhere to the requirements described in the Google Maps Platform Terms of Service, Usage and Billing, and Displaying Attributions.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Android Developer’s Guide to the Google Location Services API
Location-based applications on our mobile devices have changed the way we interact with mobile technology. The list of these applications is extensive and has had a major impact on our lives. This article walks us through a step-by-step tutorial of how to determine the location of an Android device using Google Location Services API.
Knowing your user’s location is useful information in many applications we develop and use today. There are a lot of popular location-based applications out there that are making our lives easier, as well as changing the way that we use these services. An example is the wildly popular application Foursquare, where users who frequent to an establishment and “check in” often win discounts. Uber, which helps you get a ride from your mobile phone at a lower rate than a normal taxi. The list is large and still growing.
In this article, we are going to build a simple Android application to determine the user’s latitude and longitude using Android’s Google Location Services API. When developing Android applications, there are a couple of ways to get the user’s location.
Package “android.location”
The package “android.location” has been available since Android was first introduced, and it gives us access to location services. These services allow applications to obtain periodic updates of the device’s geographical location.
The package provides two means of acquiring location data:
LocationManager.GPS_PROVIDER: Determines location using satellites. Depending on the conditions, this provider may take a while to return a location fix.
LocationManager.NETWORK_PROVIDER: Determines location based on availability of nearby cell towers and WiFi access points. This is faster than GPS_PROVIDER.
When you are looking for user location you have to play with these providers and their availability. Ideally you obtain the first location using NETWORK_PROVIDER, which might not be as accurate, but is much faster. You might then make an attempt to increase accuracy by listening for a better location fix using the GPS_PROVIDER.
The APIs provided by this package are fairly low-level, and require the developer of the application to handle the finer details of determining when to request location data and schedule calls to the API in an optimized way. To improve developer experience with location based system services and ease the process of developing location-aware applications, Google introduced a new way of requesting a user’s location using Google Play Services. It offers a simpler API with higher accuracy, low-power geofencing, and much more.
Google Location Services API
Google Location Services API, also known as FusedLocationProviderApi, is Google’s recommended way of getting a user’s location. It provides the best accuracy based on our needs. Some of the advantages of using this API over the previous one are:
Simplicity: Unlike the previous API, you no longer have to deal with multiple providers. Instead, you specify high-level needs, such as “high accuracy” or “low power”, and it will take a suitable approach.
Availability: Gives your app immediate access to the best, most recent known location. Usually this information is readily available, you just have to ask for it.
Power-efficiency: Minimizes your application’s usage of power.
Versatility: Meets a wide range of needs, from foreground uses — needing highly accurate location data, to background uses — requiring only periodic location updates with negligible power impact.
Let us build a location-based Android application using this API. For this, we will use Google’s suggested IDE for Android application development — Android Studio. Getting started with Android Studio is pretty straight forward. Their website describes the procedure involving the installation and configuration of Android Studio in great detail, including how to bootstrap your first Android application for development.
Android Studio should make things super-easy for us. However, we will need to begin by configuring the build script and adding Google Play Services as a dependency for this application. This can be done by modifying the “build.gradle” file as follows:
At the time I am writing this article, the latest version of Google Play Services available is 6.5.87. Make sure you always check for the latest version available before you start. In case newer versions comes out later down the road and you decide to update it for your own projects, test all location related features against all versions of Android you are supporting.
At this point, we should be able to start doing the actual work for our application.
Requesting Permission, Configuring AndroidManifest.xml
Androids have specific security features that would prevent any arbitrary application from requesting a precise user location. To solve this, we need to edit “AndroidManifest.xml” and add the permission we require for this application:
While we are at it, we should also define the version of Google Play Services we are using for this application:
Checking for Google Play Services Availability
Before accessing features provided by Google Play Services, we must check if the device has Google Play Services installed, and that the version is the one we intend to use (6.5.87).
This method will check for Google Play Services, and in case the device doesn’t have it installed (it’s rare, but I’ve seen such cases), it will open a dialog with the corresponding error and invite the user to install/update Google Play Services from the Google Play Store.
After the user completes the resolution provided by “GooglePlayServicesUtil.getErrorDialog()”, a callback method “onActivityResult()” is fired, so we have to implement some logic to handle that call:
Accessing Google APIs
To access Google APIs, we just need to perform one more step: create an instance of GoogleApiClient. The Google API Client provides a common entry point to all the Google Play services, and manages the network connection between the user’s device and each Google service. Our first step here is to initiate the connection. I usually call this code from “onCreate” method of the activity:
By chaining a series of method calls, we are specifying the callback interface implementation and the Location Service API that we want to use. The interface implementation, in this case “this”, will receive response to the asynchronous “connect()” method when the connection to Google Play Services succeed, fail, or become suspended. After adding this code, our “MainActivity” should look like this:
Then in our “onStart” method we call the “connect” method and wait for “onConnected” callback method be invoked:
The “onConnected” method will look like this:
This callback is fired when Google Play Services is connected, which means by then we should have the last known location. However, this location can be null (it’s rare but not impossible). In that case, what I recommend is to listen for location updates which will be covered next.
Listening for Location Updates
After you invoke “getLastLocation”, you might want to request periodic updates from the Fused Location Provider. Depending on your application, this period could be short or long. For instance, if you are building an application that tracks a user’s location while he drives, you will need to listen for updates on short intervals. On the other hand, if your application is about sharing user location with his friend, you maybe just need to request the location once in a while.
Creating a request is pretty easy — you can call this method inside the “onCreate” method:
We instantiate a new LocationRequest object. Set the interval to 20 seconds (20000 milliseconds). Furthermore, we set a throttled update rate to 5 seconds. This tells the API to provide updates every 20 seconds (preferably), but if there is a change available within a 5 second period, it should provide that too. Finally, we set the priority to “PRIORITY_HIGH_ACCURACY”, among the other available priority options: PRIORITY_BALANCED_POWER_ACCURACY, PRIORITY_LOW_POWER, PRIORITY_NO_POWER.
Once you have built the request, you are ready to start listening on location updates after “onConnected()” method has been fired:
All that remains now is to implement the callback method to satisfy the LocationListener interface:
Stop Listening for Updates
It is important to explicitly stop listening for updates when you don’t need them anymore, or if the user leaves your application. The following method should be invoked from within “onPause” callback:
… and disconnecting Google API:
Wrapping Up
As you can see, the fundamental ideas behind implementing location aware applications in Android is very simple. Moreover, with the available APIs that are both simple to use and easy to understand, it should be a no-brainer to build basic location-based applications for Android. The small sample application we have built here is meant to demonstrate exactly that. You can find the complete source code for this on GitHub. Please note that to keep things simple, the application is not handling the “onConnectionFailed” callback method.
Hopefully this tutorial will help you get started with using the Google Location Services API.
Источник
Location
In this document
Related samples
Location user drivers allow your app to publish updates to the device’s physical location through the Android location services. The API supports constellations of the Global Navigation Satellite System (GNSS), such as the Global Positioning System (GPS).
GNSS modules are receive-only devices that triangulate signals from remote satellites in order to determine an accurate physical location. Once the module collects enough satellite data to calculate an accurate position, it has a valid location (a fix ) that it can report.
Receiver modules typically connect to the host system via UART, but may use other forms of Peripheral I/O. For example, they may contain additional GPIO pins to control power management or report when the module has gained or lost a fix.
Adding the required permission
Add the required permission for the user driver to your app’s manifest file:
Creating the driver
The driver implementation is responsible for communicating with the connected hardware, monitoring for valid location changes, and reporting those changes to the framework. To create a driver:
- Create a new GnssDriver instance.
Register the driver with the UserDriverManager :
Unregister the driver when location events are not longer required.
Reporting location
Report each new location fix to the Android framework with the reportLocation() method. This method accepts a Location object, which contains the updated contents to report. Set the provider for each reported Location to LocationManager.GPS_PROVIDER .
The following table describes the Location attributes that a driver can report to the framework. Attributes marked required must be included or the framework will reject the location update:
Required Attributes | Optional Attributes |
---|---|
Accuracy Timestamp Latitude Longitude | Altitude Bearing Speed |
Converting GPS data
GPS is a commonly used constellation of GNSS satellites. GPS hardware typically reports location information as ASCII strings in the NMEA standard format. Each line of data is a comma-separated list of data values known as a sentence. While each GPS module may choose to report different portions of the NMEA protocol, most devices send one or more of the following sentences:
- GPGGA (Fix Information): Includes position fix, altitude, timestamp, and satellite metadata.
- GPGLL (Geographic Latitude/Longitude): Includes position fix and timestamp.
- GPRMC (Recommended Minimum Navigation): Includes position fix, speed, timestamp, and navigation metadata.
As an example, the GPRMC sentence takes the following format:
Using real data values, here is a sample GPRMC with the latitude, longitude, and speed portions highlighted in bold:
The following code example parses the GPRMC string format into a Location instance:
Content and code samples on this page are subject to the licenses described in the Content License. Java is a registered trademark of Oracle and/or its affiliates.
Источник