Display Name of the State along with Latitude and Longitude in Android - java

Initially I displayed the current latitude and longitude in the application using the following code:
package com.coders.location;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
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 java.util.Locale;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private android.widget.Button btnLocation;
private TextView txtLocation;
private android.widget.Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;
private boolean isContinue = false;
private boolean isGPS = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
this.txtLocation = (TextView) findViewById(R.id.txtLocation);
this.btnLocation = (Button) findViewById(R.id.btnLocation);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000); // 10 seconds
locationRequest.setFastestInterval(5 * 1000); // 5 seconds
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
#Override
public void gpsStatus(boolean isGPSEnable) {
// turn on GPS
isGPS = isGPSEnable;
}
});
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
*******************************************************
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
if (!isContinue) {
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
stringBuilder.append(wayLatitude);
stringBuilder.append("-");
stringBuilder.append(wayLongitude);
stringBuilder.append("\n\n");
txtContinueLocation.setText(stringBuilder.toString());
}
*******************************************************
if (!isContinue && mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
}
}
};
btnLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = false;
getLocation();
});
btnContinueLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = true;
stringBuilder = new StringBuilder();
getLocation();
});
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
AppConstants.LOCATION_REQUEST);
} else {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
}
}
#SuppressLint("MissingPermission")
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.GPS_REQUEST) {
isGPS = true; // flag maintain before get location
}
}
}
}
When I did this the code was working well. Then I tried to update the code as I needed to display the State of the current location as well "i.e. Display the state in where the users Phone is currently located(e.g. South Carolina, Massachusetts, California, etc.).
This was the updated code:
package com.coders.location;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
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 java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private double wayLatitude = 0.0, wayLongitude = 0.0;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private android.widget.Button btnLocation;
private TextView txtLocation;
private android.widget.Button btnContinueLocation;
private TextView txtContinueLocation;
private StringBuilder stringBuilder;
private boolean isContinue = false;
private boolean isGPS = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.txtContinueLocation = (TextView) findViewById(R.id.txtContinueLocation);
this.btnContinueLocation = (Button) findViewById(R.id.btnContinueLocation);
this.txtLocation = (TextView) findViewById(R.id.txtLocation);
this.btnLocation = (Button) findViewById(R.id.btnLocation);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000); // 10 seconds
locationRequest.setFastestInterval(5 * 1000); // 5 seconds
new GpsUtils(this).turnGPSOn(new GpsUtils.onGpsListener() {
#Override
public void gpsStatus(boolean isGPSEnable) {
// turn on GPS
isGPS = isGPSEnable;
}
});
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
*******************************************************
for (Location location : locationResult.getLocations()) {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName());
}
} catch (IOException e){
}
if (!isContinue) {
txtLocation.setText(stringBuilder.toString());
} else {
stringBuilder.append(wayLatitude);
stringBuilder.append("-");
stringBuilder.append(wayLongitude);
stringBuilder.append("\n\n");
txtContinueLocation.setText(stringBuilder.toString());
}
*******************************************************
if (!isContinue && mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(locationCallback);
}
}
}
}
};
btnLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = false;
getLocation();
});
btnContinueLocation.setOnClickListener(v -> {
if (!isGPS) {
Toast.makeText(this, "Please turn on GPS", Toast.LENGTH_SHORT).show();
return;
}
isContinue = true;
stringBuilder = new StringBuilder();
getLocation();
});
}
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
AppConstants.LOCATION_REQUEST);
} else {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
}
}
#SuppressLint("MissingPermission")
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1000: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (isContinue) {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(MainActivity.this, location -> {
if (location != null) {
wayLatitude = location.getLatitude();
wayLongitude = location.getLongitude();
txtLocation.setText(String.format(Locale.US, "%s - %s", wayLatitude, wayLongitude));
} else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
}
});
}
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.GPS_REQUEST) {
isGPS = true; // flag maintain before get location
}
}
}
}
This code now doesn't even display the current latitude and longitude. Can someone help me with this. I'm looking to display the State as well as the Lat and Long of the current location.
The lines of Code where the changes have been implemented and that seems the most relevant to my issue are marked with a long line of asterisk at the Start and End of the code which looks like this:
*******************************************************

All we need to do is add this permission in the manifest file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
And create a LocationManager instance like this:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Check if GPS is enabled or not.
And then implement LocationListener and get coordinates:
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
Here is the sample code to do so
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
if (addresses.size() > 0) {
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
}
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
+ cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
see this flow:
How do I get the current GPS location programmatically in Android?

Actually this code will not work now.
Google has deprecated the above code and now you need to use below code.
I used Retrofit
Retrofit Client
public static final String GOOGLE_ETA = "https://maps.googleapis.com/maps/";
public static Retrofit getEtaClient() {
if (retrofitEtaGoogle == null) {
retrofitEtaGoogle = new Retrofit.Builder()
.baseUrl(GOOGLE_ETA)
.client(provideOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofitEtaGoogle;
}
Api interface class
#GET("api/geocode/json?key="+ Consts.GOOGLE_API_KEY)
Call<GoogleGeoCodeApiResponseModel> getPlaceFromLatLng(#Query("latlng") String latLng);
In updateLocationUI() method
String latLng = location.getLatitude() + "," + location.getLongitude();
ApiInterface apiInterface = RetrofitClient.getEtaClient().create(ApiInterface.class);
Call<GoogleGeoCodeApiResponseModel> call = apiInterface.getPlaceFromLatLng(latLng);
call.enqueue(new Callback<GoogleGeoCodeApiResponseModel>() {
#Override
public void onResponse(Call<GoogleGeoCodeApiResponseModel> call, Response<GoogleGeoCodeApiResponseModel> response) {
if (response.body().getStatus() != null && response.body().getStatus().equals("OK")) {
addressObj = new GoogleAddressLocalModel();
addressObj.setName(response.body().getResults().get(0).getFormattedAddress());
addressObj.setLat(response.body().getResults().get(0).getGeometry().getLocation().getLat());
addressObj.setLng(response.body().getResults().get(0).getGeometry().getLocation().getLng());
for (GoogleGeoCodeApiResponseModel.AddressComponent obj : response.body().getResults().get(0).getAddressComponents()) {
for (String type : obj.getTypes()) {
if (type.contains("postal_code")) {
addressObj.setPostalCode(obj.getLongName());
} else if (type.contains("country")) {
addressObj.setCountryId(obj.getShortName());
addressObj.setCountryName(obj.getLongName());
} else if (type.contains("administrative_area_level_2")) {
addressObj.setCityName(obj.getLongName());
}
}
}
} else if (response.body().getStatus() != null) {
Log.e("ErrroGettingAddress", response.body().getStatus());
}
}
#Override
public void onFailure(Call<GoogleGeoCodeApiResponseModel> call, Throwable t) {
Log.e("ErrroGettingAddress", t.getLocalizedMessage());
}
});
}

Related

Android Studio JAVA: Send SMS of user's current location ;

I am Trying to Build an app where user can show their location and send an SMS to nearby hospital.
I am new to android studio and everything about it, but I quite made a progress with it.
I have 2 XML files, but I'll provide the JAVA CLASSES first
MapActivity.java
package maptesting.app;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.IOException;
import java.util.List;
import maptesting.app.databinding.ActivityMapBinding;
public class MapActivity<mapView> extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private ActivityMapBinding binding;
private View mapView;
private GoogleMap mMap;
private GoogleApiClient client;
private LocationRequest locationRequest;
private Location lastlocation;
private LocationManager locationManager;
private Marker currentLocationmMarker;
public static final int REQUEST_LOCATION_CODE = 99;
int PROXIMITY_RADIUS = 15000;
double latitude, longitude;
private int LOCATION_MIN_DISTANCE = 20;
private int LOCATION_MIN_TIME = 4000;
private boolean requestingLocationUpdates;
//NEW
private int FINE_LOCATION_REQUEST_CODE = 10001;
private float Geofence_Radius = 4000;
private Object CircleOptions;
//NEW SMS
private LocationListener locationListener;
private final long mTime = 1000;
private final long mDist = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMapBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
if (!isConnectedToNetwork()) {
Toast.makeText(this, "Turn on mobile data or Wifi", Toast.LENGTH_LONG).show();
finish();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapView = mapFragment.getView();
mapFragment.getMapAsync(this);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_LOCATION_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (client == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
Intent intent = getIntent();
finish();
startActivity(intent);
}
} else {
Toast.makeText(this, "Location Permission Denied", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
// View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
//locationButton.callOnClick();
}
//NEW INPUT (SMS)
LatLng msgloc = new LatLng(lastlocation.getLatitude(), lastlocation.getLongitude());
locationListener = new LocationListener()
{
#Override
public void onLocationChanged(#NonNull Location location)
{
try
{
String phoneNum = "09553625915";
String loc = String.valueOf(msgloc);
String message = "Location = " + msgloc;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNum, null, message, null, null);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void onProviderEnabled(#NonNull String provider)
{
}
public void onProviderDisabled(#NonNull String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, mTime, mDist,
(android.location.LocationListener) locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, mTime, mDist,
(android.location.LocationListener) locationListener);
}
catch (SecurityException e)
{
e.printStackTrace();
}
//END NEW INPUT (SMS)
}
private void buildGoogleApiClient() {
client = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
client.connect();
}
#Override
public void onLocationChanged(#NonNull Location location)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
lastlocation = location;
if (currentLocationmMarker != null)
{
currentLocationmMarker.remove();
}
Log.d("lat = ", "" + latitude);
Log.d("lng = ", "" + longitude);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
AddCircle(latLng, Geofence_Radius);
//markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
//currentLocationmMarker = mMap.addMarker(markerOptions);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
//mMap.animateCamera(CameraUpdateFactory.zoomBy(2));
//todo delete following lines
Object[] dataTransfer = new Object[2];
getNearbyPlacesData getNearbyPlacesData = new getNearbyPlacesData();
String url = getUrl(latitude, longitude, "hospital");
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlacesData.execute(dataTransfer);
Toast.makeText(MapActivity.this, "Showing Nearby Hospitals", Toast.LENGTH_SHORT).show();
//todo end
if (client != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(client, this);
}
}
private String getUrl(double latitude, double longitude, String nearbyPlace)
{
StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlaceUrl.append("location=" + latitude + "," + longitude);
googlePlaceUrl.append("&radius=" + PROXIMITY_RADIUS);
googlePlaceUrl.append("&type=" + nearbyPlace);
googlePlaceUrl.append("&sensor=true");
//Todo: add your google api key here
googlePlaceUrl.append("&key=" + "YOUR_API_KEY");
Log.d("MapsActivity", "url = " + googlePlaceUrl.toString());
return googlePlaceUrl.toString();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(5);
locationRequest.setFastestInterval(500);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// ORG
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(client, locationRequest, this);
}
}
private boolean checkLocationPermission()
{
if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED )
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
}
else
{
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.ACCESS_FINE_LOCATION },REQUEST_LOCATION_CODE);
}
return false;
}
else
{
return true;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private boolean isConnectedToNetwork() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
}
// Add Circle
private void AddCircle(LatLng latLng, float radius)
{
mMap.addCircle(new CircleOptions()
.center(latLng)
.radius(Geofence_Radius)
.strokeColor(Color.argb(50, 0, 0, 0))
.fillColor(Color.argb(13,0,0,0))
.strokeWidth(4));
}
What I want to see if its possible to send the user's current location to another phone after I hit the button that will also show their current location in the map.
I am willing to provide the source code if you kind sirs and ma'ams want to check my code.
Thank you

How to implement changes of the location and a rest button (Android Studio)

I'm new to android app dev and Java isn't my strongest programming language.
I able to make my user to allow their location to be access or deny to get their location longitude and latitude number. Though, I still can't figure our how to implement the precision changes of the location to either increase or decrease their coordinate number. I read all the documentation for android in this topic and still don't understand it.
Here's the code:
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import com.google.android.material.snackbar.Snackbar;
public class Locator extends AppCompatActivity {
Button back;
private final String enable = "Enable yout location for the GPS to work";
private final String loading = "GPS is starting";
private final String latAndLong = "Latitude: %s\n Longitude: %s\n";
private LocationManager lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
back = findViewById(R.id.backbutton);
back.setOnClickListener(view -> {
Intent intent = new Intent(Locator.this, MainActivity.class);
startActivity(intent);
});
}
public void getLocation(View v) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, getResources().getInteger(R.integer.requestCode));
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean isProviderEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isProviderEnabled) {
Snackbar.make(v, enable, Snackbar.LENGTH_LONG).setAction("Action",
null).show();
} else {
userLoca();
}
}
private void userLoca() {
TextView tvLocation = findViewById(R.id.textView_locator);
if (ActivityCompat.checkSelfPermission(Locator.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
tvLocation.setText(getResources().getString(R.string.location_denied));
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, getResources().getInteger(R.integer.requestCode));
} else if (ActivityCompat.checkSelfPermission(Locator.this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
tvLocation.setText(getResources().getString(R.string.location_denied));
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, getResources().getInteger(R.integer.requestCode));
} else {
tvLocation = findViewById(R.id.textView_locator);
Location current_GPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location networkLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location passiveLocation = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (current_GPS != null) {
tvLocation.setText(String.format(latAndLong, current_GPS.getLatitude(),
current_GPS.getLongitude()));
}
if (networkLocation != null) {
tvLocation.setText(String.format(latAndLong, networkLocation.getLatitude(),
networkLocation.getLongitude()));
}
if (passiveLocation != null) {
tvLocation.setText(String.format(latAndLong, passiveLocation.getLatitude(),
passiveLocation.getLongitude()));
} else {
Snackbar.make(tvLocation, loading, Snackbar.LENGTH_LONG).setAction("Action",
null).show();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
getResources().getInteger(R.integer.location_min_time),
getResources().getInteger(R.integer.location_min_dist), v -> {
});
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
getResources().getInteger(R.integer.location_min_time),
getResources().getInteger(R.integer.location_min_dist), v -> {
});
}
}
}
}
You need to implement location updates listener to this. Use the following code:
private LocationCallback locationCallback;
Call this in onCreate() or onResume() depending upon your logic
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
}
}
};
private void startLocationUpdates() {
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}

Saving Data from multiple android activity under one child in Firebase Database

I am new to Android Studio and firebase. Making an android app for my final year project. I want to save the location of the user under the username under the BusinessOwner field. I want to save the location of the user when signing in. Your help will be really appreciated
I have my firebase database like this now
I want it to be like this
BusinessOwnerRegister.java
package com.example.android.onroadsupport;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class BusinessOwnerRegister extends AppCompatActivity {
//Variables
TextInputLayout regName, regUsername, regEmail, regPhoneNo, regPassword,regFullAddress,regLandmark,regPinCode,regVoterID,regServiceType;
Button regBtn;
FirebaseDatabase rootNode;
DatabaseReference reference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_owner_register);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//Hooks to all xml elements in activity_user_register.xml
regName = findViewById(R.id.reg_name);
regUsername = findViewById(R.id.reg_username);
regEmail = findViewById(R.id.reg_email);
regPhoneNo = findViewById(R.id.reg_phoneNumber);
regPassword = findViewById(R.id.reg_password);
regBtn = findViewById(R.id.reg_btn);
regFullAddress = findViewById(R.id.reg_address);
regLandmark = findViewById(R.id.reg_landmark);
regPinCode = findViewById(R.id.reg_pinCode);
regVoterID = findViewById(R.id.reg_voterID);
regServiceType = findViewById(R.id.reg_serviceType);
}
private Boolean validateName() {
String val = regName.getEditText().getText().toString();
if (val.isEmpty()) {
regName.setError("Field cannot be empty");
return false;
} else {
regName.setError(null);
regName.setErrorEnabled(false);
return true;
}
}
private Boolean validateUsername() {
String val = regUsername.getEditText().getText().toString();
String noWhiteSpace = "\\A\\w{4,20}\\z";
if (val.isEmpty()) {
regUsername.setError("Field cannot be empty");
return false;
} else if (val.length() >= 15) {
regUsername.setError("Username too long");
return false;
} else if (!val.matches(noWhiteSpace)) {
regUsername.setError("White Spaces are not allowed");
return false;
} else {
regUsername.setError(null);
regUsername.setErrorEnabled(false);
return true;
}
}
private Boolean validateEmail() {
String val = regEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
regEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
regEmail.setError("Invalid email address");
return false;
} else {
regEmail.setError(null);
regEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePhoneNo() {
String val = regPhoneNo.getEditText().getText().toString();
if (val.isEmpty()) {
regPhoneNo.setError("Field cannot be empty");
return false;
} else {
regPhoneNo.setError(null);
regPhoneNo.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = regPassword.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
"(?=.*[a-zA-Z])" + //any letter
"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=\\S+$)" + //no white spaces
".{4,}" + //at least 4 characters
"$";
if (val.isEmpty()) {
regPassword.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
regPassword.setError("Password is too weak");
return false;
} else {
regPassword.setError(null);
regPassword.setErrorEnabled(false);
return true;
}
}
private Boolean validateFullAddress() {
String val = regFullAddress.getEditText().getText().toString();
if (val.isEmpty()) {
regFullAddress.setError("Field cannot be empty");
return false;
} else {
regFullAddress.setError(null);
regFullAddress.setErrorEnabled(false);
return true;
}
}
private Boolean validateLandmark() {
String val = regLandmark.getEditText().getText().toString();
if (val.isEmpty()) {
regLandmark.setError("Field cannot be empty");
return false;
} else {
regLandmark.setError(null);
regLandmark.setErrorEnabled(false);
return true;
}
}
private Boolean validatePinCode() {
String val = regPinCode.getEditText().getText().toString();
if (val.isEmpty()) {
regPinCode.setError("Field cannot be empty");
return false;
} else {
regPinCode.setError(null);
regPinCode.setErrorEnabled(false);
return true;
}
}
private Boolean validateVoterID() {
String val = regVoterID.getEditText().getText().toString();
if (val.isEmpty()) {
regVoterID.setError("Field cannot be empty");
return false;
} else {
regVoterID.setError(null);
regVoterID.setErrorEnabled(false);
return true;
}
}
private Boolean validateServiceType() {
String val = regServiceType.getEditText().getText().toString();
if (val.isEmpty()) {
regServiceType.setError("Field cannot be empty");
return false;
} else {
regServiceType.setError(null);
regServiceType.setErrorEnabled(false);
return true;
}
}
//This function will execute when user click on Sign up Button
public void registerBusinessOwner(View view) {
//Save data in firebase on button click
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("BusinessOwners");
if (!validateName() | !validateUsername() | !validateEmail() | !validatePhoneNo() | !validatePassword() |
!validateFullAddress() | !validateLandmark() | !validatePinCode() | !validateVoterID() | !validateServiceType()) {
return;
}
//Get all the values in Strings
String name = regName.getEditText().getText().toString();
String username = regUsername.getEditText().getText().toString();
String email = regEmail.getEditText().getText().toString();
String phoneNo = regPhoneNo.getEditText().getText().toString();
String password = regPassword.getEditText().getText().toString();
String fullAddress = regFullAddress.getEditText().getText().toString();
String landmark = regLandmark.getEditText().getText().toString();
String pinCode = regPinCode.getEditText().getText().toString();
String voterID = regVoterID.getEditText().getText().toString();
String serviceType = regServiceType.getEditText().getText().toString();
//Storing data in Firebase
MechanicHelperClass mechanicHelperClass = new MechanicHelperClass(name, username, email, phoneNo, password, fullAddress, landmark, pinCode, voterID, serviceType);
//Adding multiple users
//Adding username as unique ID
reference.child(username).setValue(mechanicHelperClass);
Toast.makeText(this, "Your Account has been Created Successfully!", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Add Your Location", Toast.LENGTH_SHORT).show();
//Calling Login screen after Sign up completed
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(intent);
finish();
}
}
MapsActivity.java
package com.example.android.onroadsupport;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.media.audiofx.BassBoost;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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;
import com.example.android.onroadsupport.databinding.ActivityMapsBinding;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.FirebaseDatabase;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
Button callLogin;
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2000;
private long FASTEST_INTERVAL = 5000;
private LocationManager locationManager;
private LatLng latLng;
private boolean isPermission;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
//Call login from map
callLogin = findViewById(R.id.callLoginFromMap);
callLogin.setOnClickListener(v -> {
Intent intent = new Intent(MapsActivity.this, BusinessOwnerLogin.class);
startActivity(intent);
});
if (requestSinglePermission()) {
// 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);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager =(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
checkLocation();
}
}
private boolean checkLocation() {
if (!isLocationEnabled()){
showAlert();
}
return isLocationEnabled();
}
private void showAlert() {
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Enable Location")
.setMessage("Your location setting is set to off \n Please enable location to" + "use this app")
.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
}
private boolean isLocationEnabled() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean requestSinglePermission() {
Dexter.withActivity(this)
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse response) {
isPermission = true;
}
#Override
public void onPermissionDenied(PermissionDeniedResponse response) {
//Check for permanent denial of permission
if (response.isPermanentlyDenied()) {
isPermission = false;
}
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
}
}).check();
return isPermission;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (latLng!=null){
mMap.addMarker(new MarkerOptions().position(latLng).title("You"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,14f));
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLocation == null){
startLocationUpdates();
}
else{
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
private void startLocationUpdates() {
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL).setFastestInterval(FASTEST_INTERVAL);
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient
,mLocationRequest,this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(#NonNull Location location) {
String msg = "Updated Location : " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
LocationHelper locationHelper = new LocationHelper(
location.getLongitude(),
location.getLatitude()
);
FirebaseDatabase.getInstance().getReference("BusinessOwners").child("Current Location")
.setValue(locationHelper).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(MapsActivity.this, "Location Saved", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MapsActivity.this, "Location Not Saved", Toast.LENGTH_SHORT).show();
}
}
});
latLng = new LatLng(location.getLatitude(),location.getLongitude());
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null){
mGoogleApiClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()){
mGoogleApiClient.disconnect();
}
}
}

Access Application context data through activities

This question can be a little complex, but I try to explain it as best I can.
Basically I am trying to get last location (lat, long) with my application, so I did something like this:
public class GoogleLocation extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleApiClient mGoogleApiClient = null;
Location mLastLocation = null;
LocationManager lm;
Double latitude;
Double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
connectLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
30);
}
}
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
longitude = location.getLongitude();
latitude = location.getLatitude();
}
Log.d("IMHERE","IMHERE");
Log.d("latitude",String.valueOf(latitude));
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
//Log.d("latitudee",String.valueOf(latitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void connectLocation(){
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.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); //this is the key ingredient
//**************************
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
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(
GoogleLocation.this, 1000);
} 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.
break;
}
}
});
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Log.d("mLastLocation",String.valueOf(location.getLatitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
It just works if it pass trough the onLocationChanged, so the first time it enters it takes some seconds to get the location, the second time I try that, my application already got a last location and it takes more 10 seconds to reach the new location.
At this point everything fine.
Now what I want to do is run this in background, thats why I changed the extends to activity, and try in background with that onLocationChanged to updated my location.
Something like in this example.
Every time my application detects a new location, I want to updated(do a setLocation or whatever in my class).
As I said I want to do this every time I start my application and this should run that in background, every time I access this class it should retrieve me the last location, and I want to access this class from different locations.
My full code:
public class GoogleLocation extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleApiClient mGoogleApiClient = null;
Location mLastLocation = null;
LocationManager lm;
Double latitude;
Double longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
connectLocation();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
30);
}
}
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
longitude = location.getLongitude();
latitude = location.getLatitude();
}
Log.d("IMHERE","IMHERE");
Log.d("latitude",String.valueOf(latitude));
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
//Log.d("latitudee",String.valueOf(latitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
public void connectLocation(){
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.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); //this is the key ingredient
//**************************
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
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(
GoogleLocation.this, 1000);
} 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.
break;
}
}
});
}
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
Log.d("mLastLocation",String.valueOf(location.getLatitude()));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
How can I do that?
FULL CODE:
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.location.Criteria;
import android.location.Location;
import com.google.android.gms.location.LocationListener;
import android.location.LocationManager;
import android.media.Image;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v7.widget.SearchView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
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.LocationCallback;
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.LocationSettingsStates;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import static android.location.Criteria.POWER_HIGH;
public class MainActivity extends Activity implements GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks, ResultCallback<LocationSettingsResult> ,LocationListener {
Double lat, lng;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent k = getIntent();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
} else {
mGoogleApiClient.connect();
}
}
protected LocationRequest createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
#Override
public void onConnected(Bundle bundle) {
Log.e("Connection", "GOOGLE API Connected");
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(createLocationRequest());
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
builder.build());
result.setResultCallback(this);
}
protected void getPhoneLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.e("Connection","GOOGLE API Suspended");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e("Connection","GOOGLE API Failed : " + connectionResult.toString() );
}
#Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
if (!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
222);
}
else
{
getPhoneLocation();
}
// All location settings are satisfied. The client can
// initialize location requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
MainActivity.this,
111);
} 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.
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("Activity","Result");
if(requestCode != 333) {
if (!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
222);
} else {
getPhoneLocation();
}
}
else
{
if(resultCode == RESULT_OK) {
finish();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if(requestCode == 222) {
if (grantResults.length != 0) {
getPhoneLocation();
}
}
}
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
}
} `
This code gets you location between 10 - 5 second intervals and they pass through onLocationChanged ... the GetLastKnowLocation gets you the last known location to the device... so sometimes it could return null...
CODE EXPLANATION
This code block in the OnCreate connects to the Google API Client with callbacks pointing back to the activity.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
} else {
mGoogleApiClient.connect();
}
THIS IS IMPORTANT
public class MainActivity extends Activity implements GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks, ResultCallback<LocationSettingsResult> ,LocationListener {
Creates A location request like yours with intervals
protected LocationRequest createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
return mLocationRequest;
}
WHEN GOOGLE API CONNECTS CHECK SETTINGS AND PERMISSIONS
#Override
public void onConnected(Bundle bundle) {
Log.e("Connection", "GOOGLE API Connected");
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(createLocationRequest());
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient,
builder.build());
result.setResultCallback(this);
}
THE SETTINGS CALLBACK RETURNS TO ACTIVITY HERE
In this block we check the status of the settings and see if they return success we check for permission ... if we have permission to access the location ... then we getPhoneLocation() OPTION A ... if we dont have permission we ask for permission and the callback goes to OPTION B
`#Override`
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
if (!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
222);
}
else
{
getPhoneLocation();
}
// All location settings are satisfied. The client can
// initialize location requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
MainActivity.this,
111);
} 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.
break;
}
}
OPTION B
In this block we get the Return from checking the user permission ... if he accepted the request for location we go on to get the PhoneLocation ... if no we close the activity.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("Activity","Result");
if(requestCode != 333) {
if (!(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
222);
} else {
getPhoneLocation();
}
}
else
{
if(resultCode == RESULT_OK) {
finish();
}
}
}
ADD THE LOCATION REQUESTS (OPTION A)
protected void getPhoneLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
NOW YOU HAVE LOCATION
Now you have the location in the given interval as long as the Activity is open.
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
}

Android Google Map How to marker Position from ArrayList

I am using google maps on my app. I have an ArrayList where has lat, long and other information. I want to make click on a marker and go to other Activity with specific marker info to show details.
I have used this code but always get the last position of ArrayList. How to get each position's information?
package com.teledaktar.activities.mapsAndLocation;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.widget.Toast;
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.CameraPosition;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.teledaktar.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Marker;
import com.teledaktar.activities.blogActivities.BlogActivity;
import com.teledaktar.activities.root.MainActivity;
import com.teledaktar.api.AppClient;
import com.teledaktar.api.ApplicationConfig;
import com.teledaktar.model.blog.BlogContent;
import com.teledaktar.model.hospital_model.Hospital;
import com.teledaktar.model.nearestHospitalModels.Hospitals;
import com.teledaktar.model.nearestHospitalModels.NearestHospitalContent;
import com.teledaktar.utility.Constants;
import java.util.ArrayList;
import dmax.dialog.SpotsDialog;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DoctorLocationOnMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener, SensorEventListener, GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
double currentLatitude, currentLongitude;
float mDeclination;
private SpotsDialog pDialog;
private Marker myMarker;
int clickPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_location_on_maps);
pDialog = new SpotsDialog(DoctorLocationOnMapsActivity.this, R.style.Custom);
pDialog.setCancelable(true);
checkLocationPermission();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#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));
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(DoctorLocationOnMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(DoctorLocationOnMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
mMap.setMyLocationEnabled(true);
}
}
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) {
buildGoogleApiClient();
// mMap.setMyLocationEnabled(true);
return;
}
// Toast.makeText(this, Double.toString(currentLattitude), Toast.LENGTH_SHORT).show();
//specify latitude and longitude of both source and destination
/*Polyline line = googleMap.addPolyline(new PolylineOptions()
.add(new LatLng(currentLattitude, currentLongitude), new LatLng(24.21,88.84))
.width(10)
.color(Color.MAGENTA));
*/
mMap.setOnMarkerClickListener(this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
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) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
return;
}
String lattitudeString = Constants.latitude;
String longitudeString = Constants.longitude;
if (lattitudeString == null) {
lattitudeString = "23.7277";
}
if (longitudeString == null) {
longitudeString = "90.4106";
}
Double hospitalLat = Double.parseDouble(lattitudeString);
Double hospitalLong = Double.parseDouble(longitudeString);
/*
LatLng bagha = new LatLng(hospitalLat,hospitalLong);
mMap.addMarker(new MarkerOptions().position(bagha).title("Marker in Hospital"));*/
/**
* find current location . latitude and longitude
*/
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation == null) {
Toast.makeText(this, "Please Enable GPS and give location permission to get dirrection ", Toast.LENGTH_SHORT).show();
} else {
currentLatitude = mLastLocation.getLatitude();
currentLongitude = mLastLocation.getLongitude();
getNearestHospitalApiData(currentLatitude, currentLongitude);
/* Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(currentLatitude, currentLongitude), new LatLng(hospitalLat, hospitalLong))
.width(10)
.color(Color.GREEN));
*/
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
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) {
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
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) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
return;
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
/*
for changing auto rotation
*/
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
float[] rotMat = new float[9];
float[] rotMat1 = new float[9];
SensorManager.getRotationMatrixFromVector(
rotMat, event.values);
float[] orientation = new float[3];
SensorManager.getOrientation(rotMat, orientation);
float bearing = (float) (Math.toDegrees(orientation[0]) + mDeclination);
updateCamera(bearing);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
private void updateCamera(float bearing) {
CameraPosition oldPos = mMap.getCameraPosition();
CameraPosition pos = CameraPosition.builder(oldPos).bearing(bearing).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(pos));
}
public void getNearestHospitalApiData(Double latitude, Double longitude) {
/**
* HERE API CALL WILL BE ADDED
*/
show();
String lats = Double.toString(latitude);
String longs = Double.toString(longitude);
final ApplicationConfig apiServiceReader = AppClient.getApiService();
Call<NearestHospitalContent> list = apiServiceReader.getNearestHospitals(lats, longs);
list.enqueue(new Callback<NearestHospitalContent>() {
#Override
public void onResponse(Call<NearestHospitalContent> call, Response<NearestHospitalContent> response) {
if (response.isSuccessful()) {
hide();
if (response.body().getStatus_code().equals("200")){
ArrayList<Hospitals> nearestHospitals = response.body().getHospitals();
if (nearestHospitals.size() > 0) {
for (int i = 0; i < nearestHospitals.size(); i++) {
Double latitudes = Double.parseDouble(nearestHospitals.get(i).getLatitude().substring(0, 5));
Double longitudes = Double.parseDouble(nearestHospitals.get(i).getLongitude().substring(0, 5));
LatLng hospitalMarker = new LatLng(latitudes, longitudes);
myMarker = mMap.addMarker(new MarkerOptions()
.position(hospitalMarker)
.title(nearestHospitals.get(i).getName())
.snippet(nearestHospitals.get(i).getDescription())
.alpha(0.8f)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
// mMap.addMarker(new MarkerOptions().position(hospitalMarker).title(nearestHospitals.get(i).getName()).alpha(0.8f));
myMarker.showInfoWindow();
Constants.NEAREST_HOSPITAL_NAME = nearestHospitals.get(i).getName();
clickPosition =i;
System.out.println("clicked"+i);
}
}else {
Toast.makeText(DoctorLocationOnMapsActivity.this, "Currently No Nearest Hospital found at this position ", Toast.LENGTH_SHORT).show();
}
}
} else {
hide();
Toast.makeText(DoctorLocationOnMapsActivity.this, "not success", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<NearestHospitalContent> call, Throwable t) {
hide();
Toast.makeText(DoctorLocationOnMapsActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onMarkerClick(final Marker marker) {
Toast.makeText(DoctorLocationOnMapsActivity.this,Integer.toString(clickPosition), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DoctorLocationOnMapsActivity.this,MainActivity.class);
startActivity(intent);
}
/* Integer clickCount = (Integer) marker.getTag();
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;
}
private void show() {
pDialog.show();
pDialog.setMessage(getString(R.string.waiting_data_string));
}
private void hide() {
pDialog.dismiss();
}
}

Categories

Resources