Google Maps API shows location, but doesn't center - java

I'm working with the Google Maps API in Android Studio 2.2.3 and for some reason the location button works, but it doesn't center. Furthermore, I get a toast with the message that there no location was found.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
getLocationPermission();
}
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionsGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful() && task.getResult() != null) {
Log.d(TAG, "onComplete: found location");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM);
} else {
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
Location currentLocation = (Location) task.getResult();
}
}
});
}
} catch (SecurityException e) {
}
}
The above code is what I to believe the code for finding the location, and then positioning the camera to that given location. I do not get any errors and when I set the LocationButton to true, and then click on it, it does center to my location.

By changing that code to
private void getDeviceLocation(){
try{
if(mLocationPermissionGranted){
Task locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
Log.d(TAG, "onComplete: location found!");
Location currentLocation = (Location) task.getResult();
float currentZoom = mMap.getCameraPosition().zoom;//edit (added line)
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(currentLocation.getLatitude(),
currentLocation.getLongitude()), DEFAULT_ZOOM));//edit (changed line)
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
}
}
I managed so get a return with a location, after I manually set the location for the device because for some reason the location doesn't get determined rightaway.
For now the problem is solved!

Tried your code.
It didn't work for me but I solved the problem.
Here is the correct code.
private void getDeviceLocation(){
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionGranted){
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful() && task.getResult() != null){
Toast.makeText(DriverMapActivity.this, "Task is successful", Toast.LENGTH_SHORT).show();
Location currentLocation = (Location) task.getResult();
mLatLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
moveCamera(mLatLng, DEFAULT_ZOOM);
}else{
Toast.makeText(DriverMapActivity.this, "Task is unsuccessful", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Toast.makeText(this, "SecurityException Found", Toast.LENGTH_SHORT).show();
}
}
So, if your app is crashing, you might wanna try this instead.

Related

How to use getCurrentLocation of fused location provider client?

I am new for Android coding, and have writen a code to get location of Android Device but failed. Nothing changed (e.g. mLastKnownLocation or cityName) after runing, and no expception. I have already checked permission and build.gradle. Could you give me advices to implement it?
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getCurrentLocation(Priority.PRIORITY_HIGH_ACCURACY,cancellationToken);
//Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>(){
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Obtain the current location of the device
mLastKnownLocation = task.getResult();
String currentOrDefault = "Current";
if (mLastKnownLocation != null) {
Log.d(TAG, "Get current location");
} else {
Log.d(TAG, "Current location is null. Using defaults.");
currentOrDefault = "Default";
// Set current location to the default location
mLastKnownLocation = new Location("");
mLastKnownLocation.setLatitude(mDefaultLocation.latitude);
mLastKnownLocation.setLongitude(mDefaultLocation.longitude);
}
String city = "CorrectCity";
try {
List<Address> address =
geocoder.getFromLocation(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude(), 1);
if(address.isEmpty())
city = "No_city";
else{
Address target = address.get(0);
if(target.getLocality()!=null)
city = target.getLocality();
else
city = target.getAdminArea();}
} catch (IOException e) {
Log.e("Exception: %s", e.getMessage());
}
cityName = city;
// Show location details on the location TextView
String msg = currentOrDefault + " Location: " +
Double.toString(mLastKnownLocation.getLatitude()) + ", " +
Double.toString(mLastKnownLocation.getLongitude())+ " " +
cityName;
locationTextView.setText(msg);
} else {
Log.d(TAG, "Current location is null. Using defaults.");
Log.e(TAG, "Exception: %s", task.getException());
/*mMap.moveCamera(CameraUpdateFactory
.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
mMap.getUiSettings().setMyLocationButtonEnabled(false);*/
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
cityName = "ErrorCity";
}
}
}
You can get your last known location using the code below
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(getContext());
fusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
if (location != null) {
// your last known location is stored in `location`
}
});
refer: https://developer.android.com/training/location/retrieve-current
Using Location Manager
LocationManager manager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
mMap.clear();
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Me"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
#Override
public void onProviderEnabled(#NonNull String provider) {
}
#Override
public void onProviderDisabled(#NonNull String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);

want get curent Adresse Location

I am developing an application that allows to retrieve the current location address using Geocoder.
this is the step to get location adresse that i follow :
check if GPS is enable on device
if it is request Location permissionspermissions else if GPS is disable on device request enable it than request permission
initialise Geocoder and get adresse latitude and logitude the get Adresse
if the GPS is Enable before clicking on button to get Location EveryThing work fine .
but the problem is when the GPS is disable whene clicking on button to get Location even if the app request to enable it and it will be enable i get this error message
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
code that i used
Onclick Methode (test if GPS enabled than call getLocation Methode)
locationButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
//Check permissions
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(5000);
locationRequest.setFastestInterval(2000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(getApplicationContext())
.checkLocationSettings(builder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response = task.getResult(ApiException.class);
Toast.makeText(HomeActivity.this, "GPS is already tured on" + response, Toast.LENGTH_SHORT).show();
getCurrentLocation();
} catch (ApiException e) {
switch (e.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException = (ResolvableApiException) e;
resolvableApiException.startResolutionForResult(HomeActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
//Device does not have location
break;
}
}
}
});
}
});
GetLocation methode
#RequiresApi(api = Build.VERSION_CODES.M)
private void getCurrentLocation() {
int picd = 0;
if (picd == 0) {
if (!checkLocationFinePermission() || !checkLocationCoarsePermission() ) {
requestLocationPermission();
} else {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
try {
//initialize geoCoder
Location location = task.getResult();
Geocoder geocoder = new Geocoder(HomeActivity.this
, Locale.getDefault());
//initialize adresse
List<Address> addresses = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1
);
//setAdresse
adresseEditText.setText(addresses.get(0).getAddressLine(0));
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "onComplete: " + e);
}
}
});
}
}

Location is null - Android

I'm creating an app, where I want to get my current location. I want to get location only once, when user opens the app. I don't need any updates, while app is open.
Here's my code.
public class MainActivity extends AppCompatActivity {
private LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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}, 1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
return;
}
fetchLocation();
}
private void fetchLocation() {
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(600);
mLocationRequest.setFastestInterval(300);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Log.d("MyTag", "Location is null");
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
Log.d("MyTag", location.getLatitude() + " " + location.getLongitude());
}
}
}
};
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.d("MyTag", "GoogleAPIClient connected");
Task<Location> task = LocationServices.getFusedLocationProviderClient(MainActivity.this).getLastLocation();
task.addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location == null) {
LocationServices.getFusedLocationProviderClient(MainActivity.this).requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
} else {
Log.d("MyTag", "My location is: " + location.getLatitude() + " : " + location.getLongitude());
}
}
}).addOnFailureListener(MainActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("MyTag", "Error message: " + e.getMessage());
}
});
}
#Override
public void onConnectionSuspended(int i) {
Log.d("MyTag", "GoogleAPIClient connection suspended");
}
})
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(MainActivity.this, 0);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
})
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
LocationServices.getFusedLocationProviderClient(MainActivity.this).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
Log.d("MyTag", "My locations is: " + location.getLatitude() + " : " + location.getLongitude());
} else {
Log.d("MyTag", "My locations is null");
}
}
});
}
}
I watched almost all stackoverflow answers, but nothing helped. I don't know where I'm doing wrong.
I read that the fused Location Provider will only maintain background location if at least one client is connected to it. I'm connecting GoogleApiClient. If you see logs, it connects successfully, but then nothing happens. Thank you.
My logs:
-- My locations is null
-- GoogleAPIClient connected

How to return current location on flutter using native android code in java

I am trying to get current location using native code for my flutter app.
It seemed more doable to implement something similar to Google Maps where the app asks the user whether they would like location turned on or not and if they say ok, then location is turned on automatically. I have been able to do this successfully but I also want to return the current location back to the flutter end. Now, I am obtaining the user action from onActivityResult() and then running the getLastLocation() method if resultCode == RESULT_OK. However, I want the flutter end to wait until the current location is obtained. I have tried using a lock mechanism but this causes the app to freeze. Currently, I have the naive implementation of just using Thread.sleep(long millis) until an affirmative result has been obtained at which point the result would be returned back to flutter.
This is the code to turn location on:
private void turnLocationOn(Context context) {
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(10000 / 2);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
.checkLocationSettings(builder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response =
task.getResult(ApiException.class);
} catch (ApiException ex) {
switch (ex.getStatusCode()) {
case LocationSettingsStatusCodes
.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException =
(ResolvableApiException) ex;
resolvableApiException
.startResolutionForResult(MainActivity.this,
LOCATION_SETTINGS_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOCATION_SETTINGS_REQUEST) {
if (resultCode == RESULT_OK)
{
Log.i(TAG, "User turned on location");
callResult = true;
} else if (resultCode == RESULT_CANCELED) {
Log.i(TAG, "User declined location setting request");
callResult = false;
// setCallResult(false);
}
}
}
This is the method that sets the current location. It is an implementation of LocationListener:
#Override
public void onLocationChanged(Location location) {
callResult = true;
currLocation = location.getLatitude() + ", " + location.getLongitude();
}
This is the Method channel that returns a result back to flutter
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
if (methodCall.method.equals("getCurrentLocation")) {
turnLocationOn(MainActivity.this);
while (!callResult) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
result.success(currLocation);
} else {
result.notImplemented();
}
}
});
...and this is from the flutter end
final String result = await platform.invokeMethod('getCurrentLocation');
resultFromCall = "SUCCESS: $result";
debugPrint(resultFromCall);

Android - How to request location update in the new API?

I was playing a bit around the new location API from google (to get latitude and longitude values):
private void getLastLocation(){
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
try {
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(getApplicationContext(), String.valueOf(latitude) + "/" + String.valueOf(longitude), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Cannot get location", Toast.LENGTH_LONG).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("LocationFetch", "Error trying to get last GPS location");
e.printStackTrace();
}
});
} catch (SecurityException e){
Log.d("LocationFetch", "Permission missing");
}
}
When I first tested this code, the location was always returning null. However, after opening Instagram (which did a location update on my phone - the geo icon appeared briefly), the location was returning my relevant longitude and latitude values.
How do I request a location update on my app using the new API to prevent location from being null or retrieve very old locations? (getLastLocation() is not enough, possibly LocationRequest?)
It is worth noting that I do not want interval updates, I want for it to happen within an Android Service when invoked once.
Firstly add this implementation in your build.gradle file
implementation 'com.google.android.gms:play-services-location:11.2.0'//include the latest version of play services
After that implement, (implements LocationListener) in your activity or fragment and after that implement its function and then
call this method in your onCreate() getLocation();
and then in this function add these lines
protected void getLocation() {
if (isLocationEnabled(MainActivity.this)) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
else
{
//prompt user to enable location....
//.................
}
}
After that in your onLocationChanged(Location location)
add these lines of code
#Override
public void onLocationChanged(Location location) {
//Hey, a non null location! Sweet!
//remove location callback:
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);
}
and you are set to go!!!!
Cheers Happy Coding
It's work for me. Based on Official docs, every 10 seconds updates the Toast and shows your location:
private FusedLocationProviderClient fusedLocationClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
#Override
protected void onResume() {
super.onResume();
startLocationUpdates();
}
private void startLocationUpdates() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
}
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
add bellow codes to onCreate method:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(2*5000);
locationCallback=new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// if (location != null) {
String Lat = String.valueOf(location.getLatitude());
String Lon = String.valueOf(location.getLongitude());
Toast.makeText(getApplicationContext(), Lat + " - " + Lon, Toast.LENGTH_SHORT).show();
// }
}
}
};
Try this code.
In gradle
implementation 'com.google.android.gms:play-services-location:16.0.0'
In code
private void turnGPSOn() {
LocationRequest mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);
LocationSettingsRequest.Builder settingsBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
settingsBuilder.setAlwaysShow(true);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
.checkLocationSettings(settingsBuilder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response =
task.getResult(ApiException.class);
if (gps.canGetLocation()) {
lat = String.valueOf(gps.getLatitude());
lon = String.valueOf(gps.getLongitude());
}
} catch (ApiException ex) {
switch (ex.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException =
(ResolvableApiException) ex;
resolvableApiException
.startResolutionForResult(SignupActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
}
});
}

Categories

Resources