How to Obtain Current Location Using Android Location Manager [Part: 2]

mobile-maps-smartphone-location-pin-business-ss

People nowadays use their smartphones for more than just making phone calls. Today, people use smartphones to share their whereabouts on social platforms using location-based apps. This basically helps them to interact with their friends, colleagues, and family while they’re on the go.

And as mentioned in first part, we explained how adding location-based features can benefit startup apps.

We also seen the process of integrating Google maps in demo. In this part, we’ll share how to obtain the current location of the device.

Getting Started

First create new project in Android Studio.

Add permission in Manifest file.

If you are using both NETWORK_PROVIDER and GPS_PROVIDER, then you need to request only the ACCESS_FINE_LOCATION permission, because it includes permission for both providers. (Permission for ACCESS_COARSE_LOCATION includes permission only for NETWORK_PROVIDER.)

Now in Gradle file, Check dependency added or not in build.gradle of main module.

Screenshot_1
implement the class from ConnectionCallbacks, OnConnectionFailedListener.

Next, check playservice available or not.

private final static int PLAY_SERVICES_REQUEST = 100;

/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}

Now Build GoogleAPIClient And It’s CallBack.

* if Google play service avaialble then build the GoogleApiClient by calling buildGoogleApiClient()

mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();




* try to connect “mGoogleApiClient” in onStart();
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}

* Status can be handle by onConnectionFailed(), onConnected() and onConnectionSuspended()

Next, Check And Turn On GPS Location By Location Dialog

* Check gps on:
final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
manager.isProviderEnabled(LocationManager.GPS_PROVIDER)

* Change Setting:

a) Create location request

private LocationRequest locationRequest;

locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);

b) Build LocationsettingRequest

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);

C) Change Location Settings.

PendingResult<LocationSettingsResult> result =LocationServices.SettingsApi.checkLocationSettings(googleApiClient,               mLocationSettingsRequest);

d) Handle result

locationsetting by implementing ResultCallback<LocationSettingsResult> interface.
To receive location update:

* Implement the activity from LocationListener which adds onLocationChanged() method

public class StartActivity extends AppCompatActivity implements LocationListener

* Create LocationRequest object by calling createLocationRequest() method in onCreate() method upon checking the play services availability.

* onToggleLocationUpdates to turn off and turn on location update

* Before turn on check location update check that app has permission  of location or not .

“(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&

ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)”

* startLocationUpdates() in onConnected() and onResume() methods.
stopLocationUpdates() in onStop().

* retrive Location in Latest location in onLocationChanged()

Start Code Integration

  • StartActivity.java
public class StartActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private final static int PLAY_SERVICES_REQUEST = 100;
private static final int RC_SETTING = 101;
private SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//tag
private static final String TAG = StartActivity.class.getSimpleName();
private Location mLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters
// UI elements
private TextView tvLocation;
private TextView tvLocationDate;
private TextView tvLocationAccuracy;
private Button btnUpdate;
private String callback = "start_update";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
initControls();
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
}
private void initControls() {
tvLocation = (TextView) findViewById(R.id.tvLocation);
tvLocationDate = (TextView) findViewById(R.id.tvLocationDate);
tvLocationAccuracy = (TextView) findViewById(R.id.tvLocationAccuracy);
btnUpdate = (Button) findViewById(R.id.btnUpdate);
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
// Resuming the periodic location updates
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
tvLocation.setText("Location permission for this app is not granted");
} else {
mLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
tvLocation.setText(latitude + ", " + longitude);
Date locationDate = new Date(mLocation.getTime());
tvLocationDate.setText(format.format(locationDate));
tvLocationAccuracy.setText(String.valueOf(mLocation.getAccuracy()));
} else {
tvLocation.setText("(Couldn't get the location. Make sure location is enabled on the device)");
}
}
}
private void startUpdate() {
// Changing the button text
btnUpdate.setText(getString(R.string.stop_location_updates));
mRequestingLocationUpdates = true;
// Starting the location updates
startLocationUpdates();
Log.d(TAG, "Periodic location updates started!");
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
/**
* Starting the location updates
*/
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
tvLocation.setText("Location permission for this app is not granted");
} else {
if (mGoogleApiClient.isConnected())
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
else if (mGoogleApiClient != null) {
tvLocation.setText("Loading....");
mGoogleApiClient.connect();
}
}
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
// Assign the new location
mLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SETTING && resultCode == RESULT_OK) {
if (callback.equalsIgnoreCase("start_update")) {
startUpdate();
} else {
onShowMap(null);
}
}
}
public void onShowMap(View view) {
int locationMode = CheckupUtils.getLocation(StartActivity.this);
if (!CheckupUtils.isGSPServiceEnabled(StartActivity.this) || locationMode != Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) {
callback = "for_map_screen";
requestToChangeSetting();
} else {
Intent intent = new Intent(StartActivity.this, MapsActivity.class);
if (mLocation != null) {
intent.putExtra("location", mLocation);
}
startActivity(intent);
}
}
/**
* Method to toggle location updates
*/
public void onToggleLocationUpdates(View view) {
if (!mRequestingLocationUpdates) {
int locationMode = CheckupUtils.getLocation(StartActivity.this);
if (!CheckupUtils.isGSPServiceEnabled(StartActivity.this) || locationMode != Settings.Secure.LOCATION_MODE_HIGH_ACCURACY) {
callback = "start_update";
requestToChangeSetting();
} else {
startUpdate();
}
} else {
// Changing the button text
btnUpdate
.setText(getString(R.string.start_location_updates));
mRequestingLocationUpdates = false;
// Stopping the location updates
stopLocationUpdates();
Log.d(TAG, "Periodic location updates stopped!");
}
}
private void requestToChangeSetting() {
Intent iStartLocation = new Intent(StartActivity.this, LocationDialog.class);
startActivityForResult(iStartLocation, RC_SETTING);
}
}
  • Activity_start.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="vertical">
<Button
android:id="@+id/btnUpdate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:onClick="onToggleLocationUpdates"
android:text="Start Update"
android:textColor="@android:color/white" />
<Button
android:id="@+id/btnShowMap"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="@color/colorPrimary"
android:onClick="onShowMap"
android:text="Show on Map"
android:textColor="@android:color/white" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Location Details"
android:textColor="@color/colorPrimary"
android:textSize="18sp"
android:textStyle="bold"
android:visibility="visible" />


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minEms="6"
android:text="Your Location"
android:textColor="@color/colorPrimary"
android:textStyle="bold" />
<TextView
android:id="@+id/tvLocation"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1.0"
android:gravity="left"
android:text="Loading...." />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minEms="6"
android:text="Updated On"
android:textColor="@color/colorPrimary"
android:textStyle="bold" />
<TextView
android:id="@+id/tvLocationDate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1.0"
android:gravity="left"
android:text="Loading...." />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minEms="6"
android:text="Accuracy (m)"
android:textColor="@color/colorPrimary"
android:textStyle="bold" />
<TextView
android:id="@+id/tvLocationAccuracy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1.0"
android:gravity="left"
android:text="Loading...." />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal"
android:visibility="gone">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Last Location"
android:textColor="@color/colorPrimary"
android:textStyle="bold" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="1.0" />
</LinearLayout>
</LinearLayout>
  • CheckingUtils
public class CheckupUtils {
public static int getLocation(final Activity context) {
int locationMode = 999;
String locationProviders;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return locationMode; //check location mode
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (locationProviders != null && locationProviders.toString().toLowerCase().contains("gps")) {
return 3;
}
return 1000;
}
}
public static boolean isGSPServiceEnabled(Context context) {
final LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
return false;
}
return true;
}
/**
* Checks whether two providers are the same
*/
public static boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
}
  • LocationDialog
public class LocationDialog extends Activity implements ResultCallback<LocationSettingsResult>, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private LocationSettingsRequest mLocationSettingsRequest;
private LocationRequest locationRequest;
GoogleApiClient googleApiClient;
private boolean isMockLocAlreadyChecked = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_locationdialog);
}
protected void buildLocationSettingsRequest() {
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
mLocationSettingsRequest = builder.build();
}
public void locationBuilder() {
buildLocationSettingsRequest();
googleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
}
public void locationDialogpopup() {
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(
googleApiClient,
mLocationSettingsRequest
);
result.setResultCallback(this);
}
@Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
final LocationSettingsStates state = locationSettingsResult.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
Intent iResult = new Intent();
setResult(RESULT_OK, iResult);
finish();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(LocationDialog.this, 0x1);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
Intent iResult1 = new Intent();
setResult(RESULT_CANCELED, iResult1);
finish();
break;
}
}
@Override
public void onConnected(Bundle bundle) {
locationDialogpopup();
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
protected void onDestroy() {
super.onDestroy();
if (googleApiClient != null)
googleApiClient.disconnect();
}
@Override
protected void onResume() {
super.onResume();
if (googleApiClient != null && !googleApiClient.isConnected()) {
googleApiClient.connect();
} else if (googleApiClient == null) {
locationBuilder();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Intent iResult = new Intent();
setResult(RESULT_OK, iResult);
finish();
} else if (resultCode == RESULT_CANCELED) {
Intent iResult = new Intent();
setResult(RESULT_CANCELED, iResult);
finish();
}
}
}

 

  • Activity_locationdialog.xml
//update location and add marker on map

<?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="@android:color/transparent"
android:orientation="vertical">

</LinearLayout>
  • MapActivity
//update location and add marker on map

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private final static int PLAY_SERVICES_REQUEST = 100;
private static final int RC_SETTING = 101;
//tag
private static final String TAG = StartActivity.class.getSimpleName();
private Location mLocation;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = true;
private LocationRequest mLocationRequest;
// Location updates intervals in sec
private static int UPDATE_INTERVAL = 10000; // 10 sec
private static int FATEST_INTERVAL = 5000; // 5 sec
private static int DISPLACEMENT = 10; // 10 meters
private GoogleMap mMap;
//Bundle data
private Location location;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Bundle bundle = getIntent().getExtras();
if (bundle != null && bundle.containsKey("location")) {
location = (Location) bundle.getParcelable("location");
}
initControls();
// First we need to check availability of play services
if (checkPlayServices()) {
// Building the GoogleApi client
buildGoogleApiClient();
createLocationRequest();
}
}
private void initControls() {
// 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);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng latLng = new LatLng(-34, 151);
if (location != null) {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
}
// Add a marker in Sydney and move the camera
mMap.addMarker(new MarkerOptions().position(latLng).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
if (mMap.getCameraPosition().zoom <= 9) {
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 15);
mMap.moveCamera(update);
} else {
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, mMap.getCameraPosition().zoom);
mMap.moveCamera(update);
}
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
// Resuming the periodic location updates
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//
//            tvLocation.setText("Location permission for this app is not granted");
} else {
mLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);
if (mLocation != null) {
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
if (mMap != null) {
mMap.clear();
// Location Changed
mMap.addMarker(new MarkerOptions().position(latLng).title("Current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
if (mMap.getCameraPosition().zoom <= 9) {
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 15);
mMap.moveCamera(update);
} else {
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, mMap.getCameraPosition().zoom);
mMap.moveCamera(update);
}
}
}
}
}
public void onShowMap(View view) {
Intent intent = new Intent(MapsActivity.this, MapsActivity.class);
if (mLocation != null) {
intent.putExtra("location", mLocation);
}
startActivity(intent);
}
/**
* Creating google api client object
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
/**
* Creating location request object
*/
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
/**
* Method to verify google play services on the device
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
/**
* Starting the location updates
*/
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            tvLocation.setText("Location permission for this app is not granted");
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
}
/**
* Stopping location updates
*/
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
/**
* Google api callback methods
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
@Override
public void onConnected(Bundle arg0) {
// Once connected with google api, get the location
displayLocation();
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
// Assign the new location
mLocation = location;
Toast.makeText(getApplicationContext(), "Location changed!",
Toast.LENGTH_SHORT).show();
// Displaying the new location on UI
displayLocation();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SETTING && resultCode == RESULT_OK) {
mRequestingLocationUpdates = true;
// Starting the location updates
startLocationUpdates();
}
}
}
  • Activity_maps.xml
<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="com.googlemapv2.MapsActivity" />
  • AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.googlemapv2">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="android.support.multidex.MultiDexApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="@string/title_activity_maps"></activity>
<activity
android:name=".dialog.LocationDialog"
android:label="@string/title_activity_maps"></activity>
<activity
android:name=".StartActivity"
android:label="@string/title_activity_location_update">
<intent-filter>



<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
AndroidManifest.xml

Now once you run the demo, it should look like this:

device-2016-10-21-152122

Next, tapping on the “start update” button, it will first ask for permission to use location if not enabled.

device-2016-10-21-152143

After giving the permission for enabling location, it will show the current location’s data.

device-2016-10-21-152221

To show the current location on Maps, tap on the “Show on Map” button.

device-2016-10-21-152235

We are done!

You have successfully added the location-based feature in your Android app.

In case you face any issue, you can contact our developers for help.

And if you’ve a startup app idea and would like to add such features, contact us to hire Android App developer.

We provide an expert team of highly experienced developers who will be specifically assigned for your app idea and convert it into a successful app.

This page was last edited on July 19th, 2017, at 18:14.
 
 

Want to Integrate Google Map in Your App? Contact us Now.

Get your free consultation now