Uploaded by Sidra Javed

Maps and Geolocation

advertisement
Maps and Geolocation:
Topic:1 Maps and places
Allow your users to explore the world with rich maps provided by Google. Identify locations
with custom markers, augment the map data with image overlays, embed one or more maps
as fragments, show details about nearby points of interest, and much more.
Maps SDK
The Maps SDK for Android is part of the Google Play services platform and lets you include maps
and customized mapping information in your app. Follow the Get Started guide to set up Google Play
services in your project, then dive into the key features of the Maps SDK.
Get Started
Maps SDK for Android Quickstart
Create an Android app that displays a map by using the Google Maps Views template for
Android Studio. If you have an existing Android Studio project that you'd like to set up,
see Set up an Android Studio project.
This quickstart is intended for developers who are familiar with basic Android development
with Kotlin or Java.
About the development environment
This quickstart was developed using Android Studio Hedgehog and the Android Gradle
plugin version 8.2.
Set up an Android device
To run an app that uses the Maps SDK for Android, you must deploy it to an Android device
or Android emulator that is based on Android 5.0 or higher and includes the Google APIs.

To use an Android device, follow the instructions at Run apps on a hardware device.

To use an Android emulator, you can create a virtual device and install the emulator by using
the Android Virtual Device (AVD) Manager that comes with Android Studio.
Create a Google Maps project in Android Studio (method1)
The procedure to create a Google Maps project in Android Studio was changed in the
Flamingo and later releases of Android Studio.
1. Open Android Studio, and click New Project in the Welcome to Android
Studio window.
2. In the New Project window, under the Phone and Tablet category, select No Activity,
and then click Next.
3. Complete the New Project form:
 Set Language to Java or Kotlin. Both languages are fully supported by the Maps
SDK for Android. To learn more about Kotlin, see Develop Android apps with Kotlin.
 Set Minimum SDK to an SDK version compatible with your test device. You must
select a version greater than the minimum version required by the Maps SDK for
Android version 19.0.x, which is Android API Level 21 ("Lollipop"; Android 5.0) or
higher.
 Set the Build configuration language to Kotlin DSL or Groovy DSL. Snippets for
both build configurations languages are shown in the following procedures.
4. Click Finish.
Android Studio starts Gradle and builds the project. This may take some time.
5. Add the Google Maps Views Activity:
a.
Right-click on the app folder in your project.
b.
Select New > Google > Google Maps Views Activity.
c.
d.
In the New Android Activity dialog box, select the Launcher Activity checkbox.
Select Finish.
6. When the build is finished, Android Studio opens
the AndroidManifest.xml and MapsActivity files. Your activity may have a different name, but
it is the one you configured during setup.
Set up your Google Cloud project
Complete the required Cloud Console setup steps by clicking through the following tabs:
Step 1
Console or Cloud SDK
Console
1. In the Google Cloud Console, on the project selector page, click Create Project to begin
creating a new Cloud project.
2. Make sure that billing is enabled for your Cloud project. Confirm that billing is enabled for
your project.
Cloud SDK
gcloud projects create "PROJECT"

gcloud projects create
Step 2
Console
Enable the Maps SDK for Android from Google cloud library
Link is: https://console.cloud.google.com/projectselector2/apis/library/maps-androidbackend.googleapis.com?utm_source=Docs_EnableAPIs&utm_content=Docs_maps-androidbackend&_gl=1*rrxmpi*_ga*NDczNzk5NDUyLjE3MTk2NDAxNzc.*_ga_NRWSTWS78N*MTcx
OTY0MDE3OS4xLjEuMTcxOTY0MzgzNC4wLjAuMA..&pli=1&supportedpurview=project
Cloud SDK
gcloud services enable \
--project "PROJECT" \
"maps-android-backend.googleapis.com"
Step 3
Console
1. Go to the Google Maps Platform > Credentials page.
Go to the Credentials page
2. On the Credentials page, click Create credentials > API key.
The API key created dialog displays your newly created API key.
3. Click Close.
The new API key is listed on the Credentials page under API keys.
(Remember to restrict the API key before using it in production.)
Cloud SDK
gcloud alpha services api-keys create \
--project "PROJECT" \
--display-name "DISPLAY_NAME"
Add the API key to your app
This section describes how to store your API key so that it can be securely referenced by your
app. You should not check your API key into your version control system, so we recommend
storing it in the secrets.properties file, which is located in the root directory of your project.
For more information about the secrets.properties file, see Gradle properties files.
To install the Secrets Gradle Plugin for Android in your Google Maps project:
1. In Android Studio, open your top-level build.gradle or build.gradle.kts file and add the
following code to the dependencies element under buildscript.
buildscript {
dependencies {
classpath "com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secretsgradle-plugin:2.0.1"
}
}
2. Open your module-level build.gradle file and add the following code to the plugins element.
plugins {
// ...
id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
}
3. In your module-level build.gradle file, ensure that targetSdk and compileSdk are set to 34.
4. Save the file and sync your project with Gradle.
5. Open the secrets.properties file in your top-level directory, and then add the following
code. Replace YOUR_API_KEY with your API key. Store your key in this file
because secrets.properties is excluded from being checked into a version control system.
6. Save the file.
MAPS_API_KEY=DEFAULT_API_KEY
7. Create the local.defaults.properties file in your top-level directory, the same folder as
the secrets.properties file, and then add the following code. The purpose of this file is to
provide a backup location for the API key if the secrets.properties file is not found so that builds
don't fail. This can happen if you clone the app from a version control system which
omits secrets.properties and you have not yet created a secrets.properties file locally to provide your
API key.
8. Save the file.
9. In your AndroidManifest.xml file, go to com.google.android.geo.API_KEY and update
the android:value attribute. If the <meta-data> tag does not exist, create it as a child of
the <application> tag.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="${MAPS_API_KEY}" />
10. In Android Studio, open your module-level build.gradle or build.gradle.kts file and edit
the secrets property. If the secrets property does not exist, add it.
11. Edit the properties of the plugin to set propertiesFileName to secrets.properties,
set defaultPropertiesFileName to local.defaults.properties, and set any other properties.
secrets {
// Optionally specify a different file name containing your secrets.
// The plugin defaults to "local.properties"
propertiesFileName = "secrets.properties"
// A properties file containing default secret values. This file can be
// checked in version control.
defaultPropertiesFileName = "local.defaults.properties"
// Configure which keys should be ignored by the plugin by providing regular expressions.
// "sdk.dir" is ignored by default.
ignoreList.add("keyToIgnore") // Ignore the key "keyToIgnore"
ignoreList.add("sdk.*")
// Ignore all keys matching the regexp "sdk.*"
Look at the code
Examine the code supplied by the template. In particular, look at the following files in your
Android Studio project.
Maps activity file
The maps activity file is the main activity for the app, and contains the code to manage and
display the map. By default, the file that defines the activity is named MapsActivity.java or if
you set Kotlin as the language for your app, MapsActivity.kt.
The main elements of the maps activity:




The SupportMapFragment object manages the lifecycle of the map and is the parent element of
the app's UI.
The GoogleMap object provides access to the map data and view. This is the main class of the
Maps SDK for Android. The Map Objects guide describes
the SupportMapFragment and GoogleMap objects in more detail.
The moveCamera function centers the map at the LatLng coordinates for Sydney Australia.
The first settings to configure when adding a map are usually the map location and camera
settings; such as viewing angle, map orientation, and zoom level. See the Camera and
View guide for details.
The addMarker function adds a marker to the coordinates for
Sydney. See the Markers guide for details.
Module Gradle file
The Module build.gradle file includes the following maps
dependency, which is required by the Maps SDK for Android.
dependencies {
// Maps SDK for Android
implementation 'com.google.android.gms:play-services-maps:19.0.0'
}
XML layout file
The activity_maps.xml file is the XML layout file that defines the
structure of the app's UI. The file is located in the res/layout directory.
The activity_maps.xml file declares a fragment that includes the following elements:

tools:context sets the default activity of the fragment to MapsActivity, which is defined in the maps
activity file.

android:name sets the class name of the fragment to SupportMapFragment, which is the fragment type
used in the maps activity file.
The XML layout file contains the following code:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />
Deploy and run the app
When you run the app successfully, it will display a map that is centered on Sydney Australia
with a marker on the city as seen in the following screenshot.
To deploy and run the app:
1. In Android Studio, click the Run menu option (or the play button icon) to run your app.
2. When prompted to choose a device, choose one of the following options:

Select the Android device that's connected to your computer.

Alternatively, select the Launch emulator radio button and choose the virtual device that
you set up.
3. Click OK. Android Studio will start Gradle to build your app, and then display the results on
your device or emulator. It can take several minutes before the app launches.
Add a map to your app (method2)
With Maps SDK for Android, you can embed maps into an activity as a fragment using an
XML snippet. This SDK offers exciting features such as 3D maps; indoor, satellite, terrain,
and hybrid maps; vector-based tiles for efficient caching and drawing; animated transitions;
and much more. Learn about how to add a map object.
The basic steps:
1. To get the SDK, obtain an API key, and add the required frameworks, follow the steps in:
a.
b.
c.
2.
3.
4.
5.
6.
7.
Set Up in the Google Cloud Console
Use an API key
Set up an Android Studio project
Add a SupportMapFragment object to the activity that will handle the map. You can add the
fragment statically or dynamically.
Implement the OnMapReadyCallback interface.
Set the layout file as the content view.
If you added the fragment statically, get a handle to the fragment.
Register the callback.
Get a handle to the GoogleMap object.
dd a SupportMapFragment object
You can add a SupportMapFragment object to your app statically or dynamically. The simplest
way is to add it statically. If you add the fragment dynamically, you can perform additional
actions on the fragment, such as removing and replacing it at runtime.
To add a fragment Statically
In the layout file of the activity that will handle the map:
1. Add a fragment element.
2. Add the name declaration xmlns:map="http://schemas.android.com/apk/res-auto". This enables the use
of maps custom XML attributes.
3. In the fragment element, set the android:name attribute
to com.google.android.gms.maps.SupportMapFragment.
4. In the fragment element, add the android:id attribute and set it to the the R.id.map resource
ID (@+id/map).
For example, here's a complete layout file that includes a fragment element:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
To add a fragment dynamically
In the activity:
1. Create a SupportMapFragment instance.
2. Commit a transaction that adds the fragment to the activity. For more info, see Fragment
Transactions.
For example:
SupportMapFragment mapFragment = SupportMapFragment.newInstance();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.my_container, mapFragment)
.commit();
Implement the OnMapReadyCallback interface
Update the activity declaration as follows:
class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
// ...
}
Set the content view
In the onCreate method of your activity, call the setContentView method and set the layout file
as the content view.
For example, if the layout file is named main.xml:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Get a handle to the fragment and register the callback
1. To get a handle to the fragment, call the FragmentManager.findFragmentById method and pass
it the resource ID of the fragment in your layout file. If you added the fragment
dynamically, skip this step because you already retrieved the handle.
2. Call the getMapAsync method to set the callback on the fragment.
For example, if you added the fragment statically:
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Get a handle to the GoogleMap object
Use the onMapReady callback method to get a handle to the GoogleMapobject. The callback is
triggered when the map is ready to receive user input. It provides a non-null instance of
the GoogleMap class that you can use to update the map.
In this example the onMapReady callback retrieves a handle to the GoogleMap object and then
a marker is added to the map:
@Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker"));
}
When you successfully build and run the app, it will display a map with a marker on Null Island (zero
degrees latitude and zero degrees longitude.
Topic:1 Customize the map
Add markers onto the map to indicate special points of interest for your users. You can define
custom colors or icons for your map markers to match your app's look and feel. To further
enhance the app, draw polylines and polygons to indicate paths or regions, or provide
complete image overlays. Learn more in the guide about how to draw markers.
Markers
Markers indicate single locations on the map. You can customize your markers by changing
the default color, or replacing the marker icon with a custom image. Info windows can
provide additional context to a marker. OR
Markers identify locations on the map. The default marker uses a standard icon, common to
the Google Maps look and feel. It's possible to change the icon's color, image or anchor point
via the API. Markers are objects of type Marker, and are added to the map with
the GoogleMap.addMarker(markerOptions) method.
Markers are designed to be interactive. They receive click events by default, and are often
used with event listeners to bring up info windows. Setting a marker's draggable property
to true allows the user to change the position of the marker. Use a long press to activate the
ability to move the marker.
By default, when a user taps a marker, the map toolbar appears at the bottom right of the
map, giving the user quick access to the Google Maps mobile app. You can disable the
toolbar. For more information, see the guide to controls.
Getting started with markers
This episode of Maps Live covers the basics of adding markers to your map using the Maps
SDK for Android.
Add a marker
The following example demonstrates how to add a marker to a map. The marker is created at
coordinates -33.852,151.211 (Sydney, Australia), and displays the string 'Marker in Sydney'
in an info window when clicked.
@Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney, Australia,
// and move the map's camera to the same location.
LatLng sydney = new LatLng(-33.852, 151.211);
googleMap.addMarker(new MarkerOptions()
.position(sydney)
.title("Marker in Sydney"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
Associate data with a marker
You can store an arbitrary data object with a marker using Marker.setTag(), and retrieve the
data object using Marker.getTag(). The sample below shows how you can count the number
of times a marker has been clicked using tags:
/**
* A demo class that stores and retrieves data objects with each marker.
*/
public class MarkerDemoActivity extends AppCompatActivity implements
GoogleMap.OnMarkerClickListener,
OnMapReadyCallback {
private final LatLng PERTH = new LatLng(-31.952854, 115.857342);
private final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private final LatLng BRISBANE = new LatLng(-27.47093, 153.0235);
private Marker markerPerth;
private Marker markerSydney;
private Marker markerBrisbane;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_markers);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/** Called when the map is ready. */
@Override
public void onMapReady(GoogleMap map) {
// Add some markers to the map, and add a data object to each marker.
markerPerth = map.addMarker(new MarkerOptions()
.position(PERTH)
.title("Perth"));
markerPerth.setTag(0);
markerSydney = map.addMarker(new MarkerOptions()
.position(SYDNEY)
.title("Sydney"));
markerSydney.setTag(0);
markerBrisbane = map.addMarker(new MarkerOptions()
.position(BRISBANE)
.title("Brisbane"));
markerBrisbane.setTag(0);
// Set a listener for marker click.
map.setOnMarkerClickListener(this);
}
/** Called when the user clicks a marker. */
@Override
public boolean onMarkerClick(final Marker marker) {
// Retrieve the data from the marker.
Integer clickCount = (Integer) marker.getTag();
// Check if a click count was set, then display the click count.
if (clickCount != null) {
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" has been clicked " + clickCount + " times.",
Toast.LENGTH_SHORT).show();
}
// Return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
}
Make a marker draggable
You can reposition a marker once its been added to the map so long as its draggable property
is set to true. Long press the marker to enable dragging. When you take your finger off the
screen, the marker will remain in that position.
Markers are not draggable by default. You must explicitly set the marker to be draggable
either with MarkerOptions.draggable(boolean) prior to adding it to the map,
or Marker.setDraggable(boolean) once it has been added to the map. You can listen for drag
events on the marker, as described in Marker drag events.
The below snippet adds a draggable marker at Perth, Australia.
final LatLng perthLocation = new LatLng(-31.90, 115.86);
Marker perth = map.addMarker(
new MarkerOptions()
.position(perthLocation)
.draggable(true));
How to get user location in Android
Step 1. Acquiring Permissions
Since using the user’s permission is a matter concerned with high privacy, first acquire the
user’s permission to use their location by requesting them for it. From Android
6.0(Marshmallow), the concept of run-time permissions was rolled in and so the same will
be used for getting permission. Any of the following permissions can be used for this:
ACCESS_COARSE_LOCATION: It provides location accuracy within a city block.
<uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION”/>
ACCESS_FINE_LOCATION: It provides a more accurate location. To do this, it needs to
do some heavy lifting so it’s recommended to use this only when we need an accurate
location.
<uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” />
In case the app needs to access the user’s location while the app is running in the
background, we need to add the following permission along with the above ones:
<uses-permission
android:name=”android.permission.ACCESS_BACKGROUND_LOCATION” />
We need to add all these permissions in the AndroidManifest.xml. To access this file, select
your project view as Android and click on:
app->manifests->AndroidManifest.xml.
After adding all the permissions, this is how the AndroidManifest.xml file looks like:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.getuserlocation">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.GetUserLocation">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>
Also, as Google’s PlayServices will be used to access the device’s location, add it in
dependencies, in the Build.Gradle (app) file:
implementation ‘com.google.android.gms:play-services-location:17.0.0’
testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘androidx.test.ext:junit:1.1.1’
androidTestImplementation ‘androidx.test.espresso:espresso-core:3.2.0’
Step 2. Designing the layout
As the app is fairly simple, it would contain only the MainActivity and hence a single main
layout. In the layout, add an ImageView and two TextViews which would be displaying the
user’s latitude and longitude. The latitude and longitude which would be displayed will be
returned from the logic of our MainActivity which will be discussed next. Here’s
how activity_main.xml looks like:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4caf50"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="120dp"
android:src="@drawable/gfgimage" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-black"
android:text="Latitude:" />
<TextView
android:id="@+id/latTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Latitude will be here! "
android:textColor="#f5f5f5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-black"
android:text="Longitude:" />
<TextView
android:id="@+id/lonTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Longitude will be here! "
android:textColor="#f5f5f5" />
OUTPUT
</LinearLayout>
Step 3. Writing the logic

To work on the main logic of our app, we will follow the following key points:
o Check if the permissions we request are enabled.
o Else request the permissions.
o If permissions are accepted and the location is enabled, get the last location of the
user.
 In order to get the last location of the user, make use of the Java public class
FusedLocationProviderClient. It is actually a location service that combines GPS
location and network location to achieve a balance between battery consumption and
accuracy. GPS location is used to provide accuracy and network location is used to get
location when the user is indoors.
 In conjunction with FusedLocationProviderClient, LocationRequest public class is used
to get the last known location. On this LocationRequest object, set a variety of methods
such as set the priority of how accurate the location to be or in how many intervals,
request of the location is to be made.
 If very high accuracy is required, use PRIORITY_HIGH_ACCURACY as an argument
to the setPriority(int) method. For a city level accuracy(low accuracy), use
PRIORITY_LOW_POWER.
 Once the LocationRequest object is ready, set it on the FusedLocationProviderClient
object to get the final location.
Let’s now look at the MainActivity.java file.
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
public class MainActivity extends AppCompatActivity {
// initializing
// FusedLocationProviderClient
// object
FusedLocationProviderClient mFusedLocationClient;
// Initializing other items
// from layout file
TextView latitudeTextView, longitTextView;
int PERMISSION_ID = 44;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latitudeTextView = findViewById(R.id.latTextView);
longitTextView = findViewById(R.id.lonTextView);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// method to get the location
getLastLocation();
}
@SuppressLint("MissingPermission")
private void getLastLocation() {
// check if permissions are given
if (checkPermissions()) {
// check if location is enabled
if (isLocationEnabled()) {
// getting last
// location from
// FusedLocationClient
// object
mFusedLocationClient.getLastLocation().addOnCompleteListener(new
OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location>
task) {
Location location = task.getResult();
if (location == null) {
requestNewLocationData();
} else {
latitudeTextView.setText(location.getLatitude() + "");
longitTextView.setText(location.getLongitude() + "");
}
}
});
} else {
Toast.makeText(this, "Please turn on" + " your location...",
Toast.LENGTH_LONG).show();
Intent intent = new
Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
} else {
// if permissions aren't available,
// request for permissions
requestPermissions();
}
}
@SuppressLint("MissingPermission")
private void requestNewLocationData() {
// Initializing LocationRequest
// object with appropriate methods
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(5);
mLocationRequest.setFastestInterval(0);
mLocationRequest.setNumUpdates(1);
// setting LocationRequest
// on FusedLocationClient
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
}
private LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
Location mLastLocation = locationResult.getLastLocation();
latitudeTextView.setText("Latitude: " + mLastLocation.getLatitude() + "");
longitTextView.setText("Longitude: " + mLastLocation.getLongitude() +
"");
}
};
// method to check for permissions
private boolean checkPermissions() {
return ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED;
// If we want background location
// on Android 10.0 and higher,
// use:
// ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
PackageManager.PERMISSION_GRANTED
}
// method to request for permissions
private void requestPermissions() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSION_ID);
}
// method to check
// if location is enabled
private boolean isLocationEnabled() {
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
// If everything is alright then
@Override
public void
onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_ID) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
}
Note: In order to see this location in
}
@Override
public void onResume() {
super.onResume();
if (checkPermissions()) {
getLastLocation();
}
}
}
OUTPUT
Google Maps, just formulate the query
as:
https://www.google.com/maps/search/
?api=1&query=37.4219983, -122.084
Getting the information about Locations
Once you have created the Location Services client you can get the last known location of a
user's device. When your app is connected to these you can use the fused location
provider's getLastLocation() method to retrieve the device location. The precision of the
location returned by this call is determined by the permission setting you put in your app
manifest, as described in the guide on how to request location permissions.
To request the last known location, call the getLastLocation() method. The following code
snippet illustrates the request and a simple handling of the response:
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// Logic to handle location object
}
}
});
The getLastLocation() method returns a Task that you can use to get a Location object with
the latitude and longitude coordinates of a geographic location. The location object may
be null in the following situations:

Location is turned off in the device settings. The result could be null even if the last location
was previously retrieved because disabling location also clears the cache.

The device never recorded its location, which could be the case of a new device or a device
that has been restored to factory settings.

Google Play services on the device has restarted, and there is no active Fused Location
Provider client that has requested location after the services restarted. To avoid this situation
you can create a new client and request location updates yourself. For more information,
see Receiving Location Updates.
Choose the best location estimate
The FusedLocationProviderClient provides several methods to retrieve device location
information. Choose from one of the following, depending on your app's use case:

getLastLocation() gets a location estimate more quickly and minimizes battery usage that can
be attributed to your app. However, the location information might be out of date, if no other
clients have actively used location recently.

getCurrentLocation() gets a fresher, more accurate location more consistently. However, this
method can cause active location computation to occur on the device
This is the recommended way to get a fresh location, whenever possible, and is safer than
alternatives like starting and managing location updates yourself
using requestLocationUpdates(). If your app calls requestLocationUpdates(), your app can
sometimes consume large amounts of power if location isn't available, or if the request isn't
stopped correctly after obtaining a fresh location.
Showing the User’s Location on Map
public abstract Task<Location> getCurrentLocation (int priority, CancellationToken
cancellationToken)
Returns a single location fix representing the best estimate of the current location of the
device. This may return a cached location if a recent enough location fix exists, or may
compute a fresh location. If unable to retrieve a current location fix before timing out, null
will be returned.
The behavior of this method can be modified in important ways through various parameters
of CurrentLocationRequest, and clients are encouraged to familiarize themselves
with CurrentLocationRequest and the getCurrentLocation(CurrentLocationRequest,
CancellationToken) overload.
See getCurrentLocation(CurrentLocationRequest, CancellationToken) for more
documentation.
public abstract
Task<Location> getCurrentLocation (CurrentLocationRequest request, CancellationT
oken cancellationToken)
Returns a single location fix representing the best estimate of the current location of the
device. This may return a cached location if a recent enough location fix exists, or may
compute a fresh location. If unable to retrieve a current location fix before timing out, null
will be returned.
Clients may supply an optional CancellationToken which may be used to cancel the
request.
This API has the same background location limits that apply to
requestLocationUpdates(LocationRequest, PendingIntent) and all location APIs, so clients
may note that this API fails to return a location more often when invoked from the
background.
There are many parameters of CurrentLocationRequest that can substantially affect the
latency and behavior of this API - in particular, clients are encouraged to select a
CurrentLocationRequest.getMaxUpdateAgeMillis() that best suits their needs, and to
review all parameters of the request to familiarize themselves with the options.
Related documents
Download