Show the current location when run map - java

How to get Current location when the app run. I know about the setMyLocationEnabled(true) and I see the many questions on stackoverflow but not get the answer perfectly.
I try this code
private GoogleMap mMap;
LocationManager locationManager;
Location location;
String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//==================================================================================================
//get user location code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
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) {
// TODO: Consider calling
return;
}
location = locationManager.getLastKnownLocation(provider);
if(location != null){
Toast.makeText(this,"Location get"+location.getLatitude()+" --- "+location.getLatitude(),Toast.LENGTH_SHORT).show();
}else{
if(location == null){
Toast.makeText(this,"Location Not get",Toast.LENGTH_SHORT).show();
}
}
//==================================================================================================
}
//==================================================================================================
// map code
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (location != null) {
//here where the camera animate and zoom to particular location.
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 14));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(15) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east// Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
// Add a marker in Sydney and move the camera
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) {
// TODO: Consider calling
return;
}
mMap.setMyLocationEnabled(true);
//==================================================================================================
}#Override
protected void onResume() {
super.onResume();
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) {
// TODO: Consider calling
return;
}
locationManager.requestLocationUpdates(provider, 4000, 1, this);
}
#Override
protected void onPause() {
super.onPause();
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) {
// TODO: Consider calling
return;
}
locationManager.removeUpdates(this);
}
//==================================================================================================
#Override
public void onLocationChanged(Location location) {
Toast.makeText(this,"Location Changed",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Toast.makeText(this,"onStatus...",Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(this,"onProvider",Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(this,"onProviderDis",Toast.LENGTH_LONG).show();
}

Related

Why is my code not getting the latitude and longitude of my location in google map

I want to create a database reference in firebase whenever a particular user is online and at the same time store the latitude and longitude of that online user into firebase database by using Geofire. I dont know why my longitude and latitude is returning null even when there is an online user.It's becoming so frustrating as I don't really know what is the issue and I have check so many suggestions from stack overflow and still can't solve it. Your helps will be really appreciated
Here is the code
public class DriversMapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private GoogleMap mMap;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private LocationRequest locationRequest;
public static final int PERMISSION_FINE_LOCATION = 99;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drivers_maps);
driverSetting = findViewById(R.id.driver_maps_setting);
logoutBtn = findViewById(R.id.driver_maps_logout);
mAuth = FirebaseAuth.getInstance();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
checkLocationPermission();
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
buildGoogleApiClient();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
locationRequest = new LocationRequest();
locationRequest.setInterval(1000);
locationRequest.setFastestInterval(1000);
locationRequest.setPriority(locationRequest.PRIORITY_HIGH_ACCURACY);
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(googleApiClient, locationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
// if (getApplicationContext()!=null){
if (lastLocation !=null){
lastLocation = location;
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12));
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
geoFireDriverAvailability.setLocation(userID,new GeoLocation(location.getLatitude(),location.getLongitude()));
}
}
protected synchronized void buildGoogleApiClient(){
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
#Override
protected void onStop() {
super.onStop();
String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference driverAvailableRef = FirebaseDatabase.getInstance().getReference().child("Drivers Available");
GeoFire geoFireDriverAvailability = new GeoFire(driverAvailableRef);
geoFireDriverAvailability.removeLocation(userID);
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(DriversMapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(DriversMapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
}
}
return true;
}
}

how to pass the the double value from a function to onCreate funtion

in my application i used mapview , there i getting longitude and latitude values in double,
so i want to pass this value to oncreate function , how to do it
private void fetchLastLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
Task<Location> task = fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null){
currentLocation = location;
Toast.makeText(getApplicationContext(), currentLocation.getLatitude()
+""+currentLocation.getLongitude(), Toast.LENGTH_SHORT).show();
//seeee here a toast , this toasting langitude and latitude double values
and how to pass these doule values to onCreate function
Address_location = Double.toString(currentLocation.getLatitude());
SupportMapFragment supportMapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(AddAddressActivity.this);
}
}
});
}

Getting Initial Coordinates at onMayReady() in Android Google Map API

I'm implementing Google Maps api in which I'm trying to get the initial location at the start at onMapReady().
mCurrentLocation should be the variable that stores the location so I tried to output that in log in onMapReady(), but at the start mCurrentLocation is null, so first I have to request a location. I'm not familiar with the api. I made a guess and put startLocationUpdates(this) in the front.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 14.0f));
// Start the update??
startLocationUpdates(this);
// This is where I want to retrieve the location coordinates
Log.w("Location", "Current reading: " + mCurrentLocation.toString());
}
It didn't work. In stack trace it says java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.location.Location.toString()' on a null object reference. I also tried other methods like initLocation() and it didn't work either.
This is rest of the code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
initLocations();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case ACCESS_FINE_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, null /* Looper */);
}
return;
}
}
}
private void initLocations() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
ACCESS_FINE_LOCATION);
}
return;
}
}
private void startLocationUpdates(Context context) {
Intent intent = new Intent(context, LocationService.class);
mLocationPendingIntent = PendingIntent.getService(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Task<Void> locationTask = mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationPendingIntent);
if (locationTask != null) {
locationTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ApiException) {
Log.w("Main2Activity", ((ApiException) e).getStatusMessage());
} else {
Log.w("Main2Activity", e.getMessage());
}
}
});
locationTask.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.d("Main2Activity", "restarting gps successful!");
}
});
}
}
}
private void stopLocationUpdates(){
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
#Override
protected void onResume() {
super.onResume();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
accelerometer.startAccelerometerRecording();
}
private Location mCurrentLocation;
private String mLastUpdateTime;
LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mCurrentLocation = locationResult.getLastLocation();
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
Log.i("MAP", "new location " + mCurrentLocation.toString());
if (mMap != null)
mMap.addMarker(new MarkerOptions().position(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()))
.title(mLastUpdateTime));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude()), 14.0f));
}
};
What is the proper way to request a location?
I'm always use the LocationManager to get the current location also make sure that your current gps is turned on.
final LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestSingleUpdate(criteria, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// this is where you get the location location.getLatitude(), location.getLongitude()
}
#Override public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override public void onProviderEnabled(String provider) { }
#Override public void onProviderDisabled(String provider) { }
}, null);
You can use this approach :
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking_order);
mService = Common.geoCodeService();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFrag = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
public void onMapReady(GoogleMap googleMap)
{
mMap=googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000); // two minute interval
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
}
}
LocationCallback mLocationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng yourLocation = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(yourLocation);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(yourLocation, 11));
//after add marker for your location add marker for this order
drawRoute(yourLocation,Common.currentRequest.getAddress());
}
}
};

How to get current location update every 10 steps moved

I have implemented this code to get current location update every 10 steps moved but I'm not getting current lat lng as i move 10 steps or more, I have question is it realistic to set minimum distance 10 steps?
Also every time when my code runs I get different different lat lng in terms of digits after decimal and if i compare these lat lng that i get every time my application runs with current location on google maps website, its roughly 400 meters away from my current location, why is it happening.
private FusedLocationProviderClient mFusedLocationClient;
private GoogleApiClient mGoogleApiClient;
private GoogleMap mMap;
private TextView tvLat;
private TextView tvLng;
Map<String, Double> latlng = new HashMap<>();
DatabaseReference data;
private double lat;
private double lng;
CameraPosition CurrentLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SingletonConnectClass instence = SingletonConnectClass.getInstance();
data = instence.firebaseSetup();
setContentView(R.layout.activity_maps);
initView();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
mFusedLocationClient
= LocationServices.getFusedLocationProviderClient(this);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
getCurrentLocation();
buildClient();
}
private void getCurrentLocation(){
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(final Location location) {
CurrentLocation = new CameraPosition.Builder().target(new
LatLng(location.getLatitude(),
location.getLongitude()))
.zoom(15.5f)
.bearing(0)
.tilt(25)
.build();
//changed camera position to current location and added marker there
}
Here is the code for getting current location update if i move 10 steps after connecting to play services in onConnected callback
public void onConnected(Bundle bundle) {
mFusedLocationClient.requestLocationUpdates(requestLocation(),
new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (final Location location : locationResult.getLocations()) {
//not getting changing current lat lng if i move 10 steps
tvLat.setText(Double.toString(location.getLatitude()));
tvLng.setText(Double.toString(location.getLongitude()));
lat = location.getLatitude();
lng = location.getLongitude();
//as result not camera position is not changed
changeCameraPosition(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLong)
}}, Looper.myLooper());
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (android.os.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);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#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_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
//stop location updates
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
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) {
// permission was granted. Do the
// contacts-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
// Permission denied, Disable the functionality that depends on this permission.
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other permissions this app might request.
// You can add here other case statements according to your requirement.
}
}
}

Download the last location at any time, and putting the subsequent markers

For several days I try to modify the program so that each time you press the button addMarkerButton program put the Marker in my new location.
When I turn on the application at once to display me my location without any buttons at all times navigate where currently I am, and when you press the addMarkerButton program put a marker in my new location, when I go to another place, and I press addMarkerButton wants a second marker at a second location but that one did not disappear.
Is it possible? I've tried a lot of combinations, looking for help on the internet and nothing.
My button looks like this (currently only for 2 markers):
addMarkerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
if (tab[0] == null) {
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am");
tab[0] = mMap.addMarker(options);
}
else if (tab [0] != null) {
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("I am");
tab[1] = mMap.addMarker(options);
In his application I use:
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
so I have:
#Override
public void onConnected(Bundle bundle) {
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;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (LocationListener) this);
}
else {
handleNewLocation(location) ;
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
The method onMapReady() I set mGoogleApiClient.connect()
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mGoogleApiClient.connect();
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;
}
}
method of downloading location:
public void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
currentLatitude = location.getLatitude();
currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
and the addition in the method onCreate()
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);

Categories

Resources