My google maps app is sending my coordinates every 5 seconds after I click the button (mapbttn). I want to make another button to stop sending these coordinates. How can I do that?
Here is my .java file:
private GoogleMap mMap;
Button mapbttn;
private LocationManager locationManager;
private LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapbttn = (Button) findViewById(R.id.setRangeButton);
mapbttn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btncoord();
}
});
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(), "" + location.getLatitude() + '\n' + location.getLongitude(), Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
public void onProviderDisabled(String s) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
return;
} else {
btncoord();
}
}
Bundle save = getIntent().getExtras();
if (save != null) color = save.getString("marker color");
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 10:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
btncoord();
return;
}
}
public void btncoord() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 5000, 0, locationListener);
}
Simply un-register your location manager like
locationManager.removeUpdates(ActivityName.this);
docs
Try this
public void stopUpdates(){
locationManager.removeUpdates(context);
}
call stopUpdate() method on stop button.
Related
How do i assign a value to GoogleMap mMap;
it is showing null pointer exception when trying to run my activity and i think that means i have to assign a value to mMap how do i do that
this is the error i am getting
Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
this is my code
public class RideHailActivity extends FragmentActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener
{
private GoogleMap mMap;
private final int MY_PERMISSION_REQUEST_CODE = 7000;
private final int PLAY_SERVICES_RES_REQUEST = 7001;
private LocationRequest locationRequest;
private GoogleApiClient googleApiClient;
private Location lastLocation;
private static int UPDATE_INTERVAL = 5000;
private static int FASTEST_INTERVAL = 3000;
private static int DISPLACEMENT = 10;
DatabaseReference reference;
GeoFire geoFire;
Marker current;
MaterialAnimatedSwitch locationSwitch;
SupportMapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ride_hail);
MapsInitializer.initialize(getApplicationContext());
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) mapFragment.getMapAsync(this);
locationSwitch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
locationSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean isOnline) {
if (isOnline) {
startLocationUpdates();
displayLocation();
}else {
stopLocationUpdates();
current.remove();
}
}
});
reference = FirebaseDatabase.getInstance().getReference("biker");
geoFire = new GeoFire(reference);
setUpLocation();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults [0] == PackageManager.PERMISSION_GRANTED) {
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
if (locationSwitch.isChecked()) displayLocation();
}
}
}
}
private void setUpLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
},MY_PERMISSION_REQUEST_CODE);
}else {
if (checkPlayServices()) {
buildGoogleApiClient();
createLocationRequest();
if (locationSwitch.isChecked()) displayLocation();
}
}
}
private void createLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setInterval(UPDATE_INTERVAL);
locationRequest.setFastestInterval(FASTEST_INTERVAL);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RES_REQUEST).show();
else {
Toast.makeText(this, "This device is not supported", Toast.LENGTH_SHORT).show();
finish();
}
return false;
}
return true;
}
private void stopLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
private void displayLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
if (locationSwitch.isChecked()) {
final double latitude = lastLocation.getLatitude();
final double longitude = lastLocation.getLongitude();
geoFire.setLocation(FirebaseAuth.getInstance().getCurrentUser().getUid(), new GeoLocation(latitude, longitude), new GeoFire.CompletionListener() {
#Override
public void onComplete(String key, DatabaseError error) {
if (current != null) current.remove();
current = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_bike))
.position(new LatLng(latitude, longitude))
.title("You"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude),15.0f));
rotateMarker(current, -360, mMap);
}
});
}
}
else {
Log.d("ERROR", "Cannot get your location");
}
}
private void rotateMarker(final Marker current, final float i, GoogleMap googleMap) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final float startRotation = current.getRotation();
final long duration = 1500;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable() {
#Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float)elapsed/duration);
float rot = t*i+(1-t)*startRotation;
current.setRotation(-rot >180?rot/2:rot);
if (t<1.0) {
handler.postDelayed(this,16);
}
}
});
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
private void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
public void onConnected(#Nullable Bundle bundle) {
displayLocation();
startLocationUpdates();
}
#Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
lastLocation = location;
displayLocation();
}
}
thanks is advance
In your activity activity Xml,add a Mapview then initialize
MapView mMapView;
static final GoogleMap[] googleMap = new GoogleMap[1];
static LatLng mypos = new LatLng(0, 0);
void init_map(final Activity act, Bundle saved_inst)
{
//you need to have intialized mMapview from your layout
mMapView.onCreate(saved_inst);
mMapView.onResume(); // needed to get the map to display immediately
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap[0] = mMap;
if (ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
ActivityCompat.requestPermissions(act,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
99);
} else {
googleMap[0].setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mypos = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder().target(mypos).zoom(10).build();
googleMap[0].animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
googleMap[0].setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
}
});
googleMap[0].setMyLocationEnabled(true);
googleMap[0].setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
}
});
}
you then call it like this from your oncreate
init_map(this,savedInstanceState);
this is assuming you have already set the api key from the manifest
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_api_key" />
to get started on geting an API key see https://developers.google.com/maps/documentation/android-sdk/get-api-key
i am trying to develop a speedometer app for testing purposes i have already written the code that will get the speed but i am not sure if it is the real time speed because sometimes i see that there's some delay, this is my code:
public class MainActivity extends AppCompatActivity {
LocationManager locationManager;
LocationListener locationListener;
public void startListening() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
public void updateLocationInfo(Location location){
TextView speedtextView = (TextView) findViewById(R.id.speedTextView);
speedtextView.setText("Current speed: " + location.getSpeed()*3600/1000);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startListening();
}
}}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateLocationInfo(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
updateLocationInfo(location);
}
}
}
}
do i have to do anything else? is there any special way to get the real time speed? because i have used a lot of apps that gets the real time speed and right now i am wondering how did they do it? could it possibly be the "fair" GPS connection? or am i doing it wrong?
I am new in this field and I am trying to make application to track my friends like "snap-map". I am able to get my real-time location but I don't know what should I add to get real-time location of people who are using same application.
Here is my Java code, it will really helpful for me if you guys give me a code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private FirebaseAuth mAuth;
final static int PERMISSION_ALL = 1;
final static String[] PERMISSIONS = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};
private GoogleMap mMap;
MarkerOptions mo;
Marker marker;
private Location user;
LocationManager locationManager;
private HashMap<Float, Location> otherUser = new HashMap<Float, Location>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mAuth = FirebaseAuth.getInstance();
// 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);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mo = new MarkerOptions().position(new LatLng(0, 0)).title("My Current Location");
if (Build.VERSION.SDK_INT >= 27 && !isPermissionGranted()) {
requestPermissions(PERMISSIONS, PERMISSION_ALL);
} else requestLocation();
if (!isLocationEnabled())
showAlert(1);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
marker = mMap.addMarker(mo);
}
//Called when the location has changed.
#Override
public void onLocationChanged(Location location) {
LatLng myCoordinates = new LatLng(location.getLatitude(), location.getLongitude());
marker.setPosition(myCoordinates);
mMap.moveCamera(CameraUpdateFactory.newLatLng(myCoordinates));
}
//Called when the provider status changes.
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
//Called when the provider is enabled by the user.
#Override
public void onProviderEnabled(String provider) {
}
//Called when the provider is disabled by the user. If requestLocationUpdates
#Override
public void onProviderDisabled(String provider) {
}
private void requestLocation() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_HIGH);
String provider = locationManager.getBestProvider(criteria, true);
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;
}
locationManager.requestLocationUpdates(provider, 10000, 10, this);
}
private boolean isLocationEnabled() {
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
private boolean isPermissionGranted() {
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED || checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
Log.v("mylog","Permission is granted");
return true;
}else{
Log.v("mylog","Permission not granted");
return false;
}
}
private void showAlert(final int status) {
String message, title, btnText;
if (status == 1) {
message = "Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
"use this app";
title = "Enable Location";
btnText = "Location Settings";
} else {
message = "Please allow this app to access location!";
title = "Permission access";
btnText = "Grant";
}
final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(false);
dialog.setTitle(title)
.setMessage(message)
.setPositiveButton(btnText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
if (status == 1) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(myIntent);
} else
requestPermissions(PERMISSIONS, PERMISSION_ALL);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
finish();
}
});
dialog.show();
}
I have a location class which creates an instance on MapFragment, and dependant on which activity the map is created from, will drop a different marker. I would also like the map to display a marker for the phones current location.
I'm assuming I can do something like this, but I cant work out how to get and update the phones current coordinates and assign that to myLocation.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
MapFragment googleMap = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
googleMap.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap nMap){
if(MainMenu.bkSource == true) {
LatLng bkLatLng = new LatLng(54.5816008, -5.9651271);
LatLng myLocation = new LatLng(???);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("Burger King, Boucher Road"));
nMap.addMarker(new MarkerOptions().position(myLocation).title("You Are Here");
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
if(MainMenu.kfcSource == true){
LatLng bkLatLng = new LatLng(54.5771914, -5.9620562);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("KFC, Boucher Road"));
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
if(MainMenu.mcdSource == true){
LatLng bkLatLng = new LatLng(54.5879486, -5.9580009);
nMap.addMarker(new MarkerOptions().position(bkLatLng).title("McDonald's, Boucher Road"));
nMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bkLatLng, 15));
nMap.animateCamera(CameraUpdateFactory.zoomTo(18.0f));
}
}
Here is an example Fragment that extends SupportMapFragment, on launch it will get the user's current location, place a Marker, and zoom in:
public class MapFragment extends SupportMapFragment
implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onPause() {
super.onPause();
//stop location updates when Activity is no longer active
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.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(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {}
#Override
public void onConnectionFailed(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_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
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.
new AlertDialog.Builder(getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
#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, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
}
Since the Location permission request needs to go through the Activity, you will need to route the result from the Activity to the Fragment's onRequestPermissionsResult() method:
public class MainActivity extends AppCompatActivity {
MapFragment mapFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapFragment = new MapFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.mapframe, mapFragment);
transaction.commit();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
if (requestCode == MapFragment.MY_PERMISSIONS_REQUEST_LOCATION){
mapFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
The layout just contains a FrameLayout where the MapFragment goes.
activity_main.xml:
Use the following code for get current location:
#Override
public void onMapReady(GoogleMap googleMap) {
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
// 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);
}
If you want to add marker in current Location try this:
1.Implement LocationListener In your Activity.
2.Update LocationRequest:
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000); //5 seconds
mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
3.create your marker on onLocationChanged(Location location)
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
//place marker at current position
//mGoogleMap.clear();
Marker currLocationMarker;
if (currLocationMarker != null) {
currLocationMarker.remove();
}
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));
currLocationMarker = mMap.addMarker(markerOptions);
}
}
I am trying to obtain a user's longitude and latitude when a button is clicked.
The following code obtains the GPS when the app is first installed, however, when the app is closed and reopened, it does not obtain any location.
I'm not sure if I incorrectly wrote the code to obtain the GPS location or I am missing something. Any advice would be appreciated.
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
private LocationManager locationManager
private LocationListener locationListener;
private double longitude;
private double latitude;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById((R.id.button2));
editText = (EditText) findViewById((R.id.editText2));
//My code
textView = (TextView) findViewById((R.id.textView2));
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
textView.append(("\n" + 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) {
Intent intent = new Intent((Settings.ACTION_LOCATION_SOURCE_SETTINGS));
startActivity(intent);
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.INTERNET
}, 10);
//return;
}
}
else {
configureButton();
}
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
configureButton();
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case 10:
if (grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
configureButton();
}
return;
}
}
private void configureButton() {
/* button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
});*/
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
}
Just just need to request location updates if the user has already granted the Location permission:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.INTERNET
}, 10);
} else {
//Added:
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
}
else {
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}