Hire the author: Dennis M

location dialog settings Image Source https://i.stack.imgur.com/j6L2D.png.

Here is the GitHub – android-google-maps-location-dialog-box link for this project.

Introduction

If you want to show your current location on a map or search maps near you. Location services on your android device are required to be ON. Today we are going to learn about how to show location request settings dialog in our own android applications like Google map, Uber, etc.

Firstly, what is the location settings dialog?

The location settings dialog lets you turn your locations settings ON directly from here without leaving from your own app to the settings of the device. Before that, we all navigated the user to the device’s location settings to enable GPS. But by using this dialog we can let the user turn it on or off within our app. it’s pretty cool, isn’t it?

What motivated me in doing this project? “How to show enable location dialog without navigating to settings page, like Google Maps in Android”. I developed an android app that uses google maps and users are required to turn on location before moving to the next activity. This blog post will provide clear and precise instructions on how to implement this dialog in android app activity. Let’s see how to do this quickly.

How to Get Started

This guide is a quick start to adding a map to an Android app. Android Studio is the recommended development environment for building an app with the Maps SDK for Android and below are a few resources to get you prepared before starting this project:

Photo Preview

Glossary

Google Maps is a web mapping service developed by Google. It offers satellite imagery, aerial photography, street maps, 360° interactive panoramic views of streets, real-time traffic conditions, and route planning for traveling by foot, car, bicycle, and air, or public transportation.

Dialog box is a graphical control element in the form of a small window that communicates information to the user and prompts them for a response.

Steps:

Step 1: 

Firstly, create a Google Maps project as shown here and go to the maps activity or the activity where you want to show this dialog and do this

private GoogleMap mMap;
private GoogleApiClient googleApiClient;
final static int REQUEST_LOCATION = 199;

Step 2: 

Secondly, in the onCreate method declare the enableLoc() function like this:

enableLoc();

This function is responsible for displaying the Enable Location Dialog Box.

Step 3: 

Thirdly, Below the onCreate method initialize the enableLoc() function like this:

private void enableLoc() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(MapsActivity.this)
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("Location error","Location error " + connectionResult.getErrorCode());
}
}).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(MapsActivity.this, REQUEST_LOCATION);
// finish();
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
}
}
});
}
}

Step 4:

After doing all the works and before running the application your full class code should look like the following:

package com.example.locationdialogbox;
import androidx.fragment.app.FragmentActivity;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
final static int REQUEST_LOCATION = 199;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//enable Gps method
enableLoc();
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private void enableLoc() {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(MapsActivity.this)
.addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("Location error","Location error " + connectionResult.getErrorCode());
}
}).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(MapsActivity.this, REQUEST_LOCATION);
// finish();
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
}
}
});
}
}
}

So now if you run your application and open this activity and if your GPS settings are off you should see a dialog.

Reflective Analysis

In conclusion, we learn about how GoogleApiClient is with a variety of static methods. Some of these methods require GoogleApiClient  connection. Importantly, the methods will queue up calls before GoogleApiClient is connected. Checking the specific API documentation to determine whether the connection is in use. Therefore, LocationRequest objects are for requesting quality of service for location updates. In conclusion, FusedLocationProviderApi has very strong services.

Future Directions

After that, add location-picker and allow users to find the current location of an android device and display details of the place (a business or other point of interest) at that location using the Maps SDK for Android, the Places SDK for Android, and the fused location provider in the Google Play services location APIs.

Learning Strategies and Tools

One of the unique features of mobile applications is location awareness. Mobile users take their devices with them everywhere. Therefore, adding location awareness to your app offers users a more contextual experience. The location APIs available in Google Play services facilitate adding location awareness to your app. For instance with automated location tracking, Geo-fencing, and activity recognition.

In conclusion, it took me a total of 20 hours to finish the project and the blog.  Finally, everything is available in this GitHub repository.

Link to the previous post blog.learningdollars.com.

Happy Coding!

Hire the author: Dennis M