I am setting up my map to track my location. Right at the start I want it to detect my Lat and Long and show where I am and update the marker location when I move.
When I test this on GenyMotion emulator and input my own positions, it works and shows updated location accordingly. But when I test it on a mobile device, I do not get any marker and get the "Location null" Toast message.
Since it is the first time on the device, there is probably no last known location. Thus wanting to make sure, I took the device and moved a distance (probably 50 meters or so back n forth) and still nothing updated on the device.
public class TrackMapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
LocationManager locationManager;
Location location;
String provider;
Double lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_track_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);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
try {
//Get last known user location
location = locationManager.getLastKnownLocation(provider);
if(location != null){
Toast.makeText(TrackMapsActivity.this, "Location NOT null", Toast.LENGTH_SHORT).show();
onLocationChanged(location);
}
else {
Toast.makeText(TrackMapsActivity.this, "Location null", Toast.LENGTH_SHORT).show();
}
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
#Override
protected void onResume() {
super.onResume();
try {
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
try {
locationManager.removeUpdates(this);
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(TrackMapsActivity.this, "You Moved", Toast.LENGTH_SHORT).show();
lat = location.getLatitude();
lng = location.getLongitude();
LatLng yourLocation = new LatLng(lat, lng);
if(mMap != null) {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Your Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(yourLocation, 10));
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
do you put the permission for using the gps :)
The main permissions you need are
android.permission.ACCESS_COARSE_LOCATION or
android.permission.ACCESS_FINE_LOCATION.
Related
I'm a student currently learning and try to play around with google map api. Right now, I'm facing a problem with the getting the location lat, long. Yesterday, I can use it just fine, but suddenly I cannot use it anymore today. The code is kinda long, because I wanted to show that the app asked for permission for the location to be turn on before using the apps but I don't think I get it correctly. I don't think the app starts like how I wanted it to start.
The process should be, from previous activity intent to this MapsActivity will prompt the request permission to open location, and once the location is on, the google map marker will update to the current location.
Right now, the apps just keeps on crashing.
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
FusedLocationProviderClient mFusedLocationClient;
LocationRequest mLocationRequest;
LocationCallback mLocationCallback;
double mLocationLat, mLocationLong;
LocationSettingsRequest.Builder mLocationSettingsBuilder;
SettingsClient client;
Task<LocationSettingsResponse> task;
private static final int REQUEST_CHECK_SETTINGS = 0x1;
#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);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//toolbar.setTitle("AskForMech : Maps");
//toolbar.setLogo(R.drawable.ic_launcher);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MapsActivity.this);
mLocationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
if(locationResult==null){
return;
} else {
mLocationLat = locationResult.getLastLocation().getLatitude();
mLocationLong = locationResult.getLastLocation().getLongitude();
}
}
};
setLocationRequestSettings();
}
public void getLocation(){ //error is here
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mLocationLat = location.getLatitude();
mLocationLong = location.getLongitude();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
getLocation(); //error is here
LatLng pos = new LatLng(mLocationLat, mLocationLong);
mMap.addMarker(new MarkerOptions().position(pos).title("You!"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(pos));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(pos, 18.00f));
}
#Override
protected void onResume() {
super.onResume();
//startLocationUpdate();
requestLocationUpdate();
}
#Override
protected void onPause() {
super.onPause();
if(mFusedLocationClient != null){
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
Toast.makeText(MapsActivity.this, "Listener is removed.", Toast.LENGTH_SHORT).show();
}
}
private void requestLocationUpdate(){
mLocationSettingsBuilder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
client = LocationServices.getSettingsClient(MapsActivity.this);
task = client.checkLocationSettings(mLocationSettingsBuilder.build());
task.addOnSuccessListener(MapsActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
startLocationUpdate();
}
});
task.addOnFailureListener(MapsActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if(e instanceof ResolvableApiException){
try{
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MapsActivity.this, REQUEST_CHECK_SETTINGS);
}catch(IntentSender.SendIntentException sendEx) {
}
}
}
});
}
private void setLocationRequestSettings(){
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(3000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void startLocationUpdate(){
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(MapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MapsActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
showExplanation();
} else {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
0);
}
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
Toast.makeText(MapsActivity.this, "Location permission was granted!", Toast.LENGTH_SHORT).show();
}
}
private void showExplanation(){
AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this);
builder.setTitle("Requires Location Permission.");
builder.setMessage("This app needs location permission to get the location information.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
0);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MapsActivity.this, "Sorry, this function cannot be used until permission is granted.",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
}
you should use the callback method onLocationChanged() instead of getLastKnownLocation (). Indeed, getLastKnownLocation() can return null (see here)
I prefer to use onLocationChanged() that is called once a location change is detected. It turns out that it works great for me.
If you have any trouble to implement a LocationListener, take a look at this post : https://stackoverflow.com/a/42218626/3780625
Best
I was trying to make a map activity app which when run, displays user's GPS' location on a map using a marker. However, on running, it just displays the marker in the default location (Sydney) please help. Below is my code.. I have tried a number of ways but all of them still lead me to Sydney. What Im trying to do is for the app to take me directly to my location once run.
Below is my code;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_real_time_location);
// 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);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PackageManager.PERMISSION_GRANTED);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PackageManager.PERMISSION_GRANTED);
}
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
try {
latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(latLng).title("My Current Position"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}
catch (SecurityException e){
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_UPDATE_TIME, MIN_UPDATES_DISTANCE, locationListener);
}
catch (SecurityException e){
e.printStackTrace();
}
}
Use LocationCallback instead to get your latest location:
LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
//The last location in the list is the newest
Location location = locationList.get(locationList.size() - 1);
Log.i(TAG, "Location " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Create instance for current user lat and lng
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// Add user position marker
currentUserPositionMarker(latLng);
//move map camera
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CURRENT_MAP_ZOOM));
}
}
};
/**
* Add Marker for user current position
*
* #param latLng current lat and lng of user
*/
private void currentUserPositionMarker(LatLng latLng) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(CURRENT_POSITION);
mCurrLocationMarker = gMap.addMarker(markerOptions);
//move map camera
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, CURRENT_MAP_ZOOM));
}
#Override
public void onPause() {
super.onPause();
if (mFusedLocationProviderClient != null) {
mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
}
#SuppressLint("MissingPermission")
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
gMap.getUiSettings().setMapToolbarEnabled(false);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(SET_INTERVAL_FOR_ACTIVE_LOCATION_UPDATES); // 3 seconds interval
mLocationRequest.setFastestInterval(SET_INTERVAL_FOR_ACTIVE_LOCATION_UPDATES);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (isFineLocationPermissionGranted())
mFusedLocationProviderClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
You need to get the last known location of the device, use this link to get the last known location, and then display the marker where you want.
I am not sure whether the title of the question is correct but here's my problem.
I have an application with Sign up and Log in. The users have different functionalities based on their log in. All the users are led to the MapsActivity.java once they log in. I am differentiating the users there and setting the display accordingly.
What I want is if the user is logged in as xyz#gmail.com, other users shall be able to see the location of that user. It is working but on one phone. When I log in as xyz#gmail.com, the location is stored in the sharedpreferences and is also retrieved when I log in as other user on the same phone.
But when I log in as xyz#gmail.com from another phone and log in as other user from another phone (2 phones - 2 users), the phones aren't connected to each other. The xyz#gmail.com location can't be seen on the other phone.
So what am I doing wrong? How do I run the same application on 2 phones simultaneously?
Hope you understand my problem. Below is my MapsActivity.java to further clarify my problem.
Thank you.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager locationManager;
private LocationListener locationListener;
private Marker mLocationMarker;
public FirebaseUser user;
public Circle circle;
#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);
user = FirebaseAuth.getInstance().getCurrentUser();
if(!user.getEmail().equalsIgnoreCase("xyz#gmail.com"))
{
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
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;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
if(mLocationMarker != null)
{
mLocationMarker.remove();
}
if(circle != null)
{
circle.remove();
}
circle = mMap.addCircle(new CircleOptions().center(latLng).radius(15).strokeColor(Color.BLUE).fillColor(Color.BLUE));
SharedPreferences sp = getSharedPreferences("MapsActivity.java", MODE_PRIVATE);
Double la = Double.longBitsToDouble(sp.getLong("la", Double.doubleToLongBits(-1)));
Double lo = Double.longBitsToDouble(sp.getLong("lo", Double.doubleToLongBits(-1)));
mLocationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(la, lo)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 1500, null);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
if(mLocationMarker != null)
{
mLocationMarker.remove();
}
if(circle != null)
{
circle.remove();
}
circle = mMap.addCircle(new CircleOptions().center(latLng).radius(15).strokeColor(Color.BLUE).fillColor(Color.BLUE));
SharedPreferences sp = getSharedPreferences("MapsActivity.java", MODE_PRIVATE);
Double la = Double.longBitsToDouble(sp.getLong("la", Double.doubleToLongBits(-1)));
Double lo = Double.longBitsToDouble(sp.getLong("lo", Double.doubleToLongBits(-1)));
mLocationMarker = mMap.addMarker(new MarkerOptions().position(new LatLng(la, lo)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 1500, null);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
else
{
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
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;
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
LatLng lolo = new LatLng(lat, lon);
if(mLocationMarker != null)
{
mLocationMarker.remove();
}
mLocationMarker = mMap.addMarker(new MarkerOptions().position(lolo));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lolo, 14), 1500, null);
SharedPreferences sp = getSharedPreferences("MapsActivity.java", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putLong("la", Double.doubleToLongBits(lat));
edit.putLong("lo", Double.doubleToLongBits(lon));
edit.apply();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
LatLng lolo = new LatLng(lat, lon);
if(mLocationMarker != null)
{
mLocationMarker.remove();
}
mLocationMarker = mMap.addMarker(new MarkerOptions().position(lolo));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lolo, 14), 1500, null);
SharedPreferences sp = getSharedPreferences("MapsActivity.java", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putLong("la", Double.doubleToLongBits(lat));
edit.putLong("lo", Double.doubleToLongBits(lon));
edit.apply();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
}
/**
* 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;
}
}
I am trying to get the current location of user and show a marker on the MAP. Here is my code
public class MapsActivity extends AppCompatActivity implements LocationListener, OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
String provider;
Location mLocation;
#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);
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
// 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;
}
mLocation=locationManager.getLastKnownLocation(provider);
if (mLocation != null) {
Log.i("Location Status: ", "Location Found");
} else if (mLocation == null) {
Log.i("Location Status: ", "Location Not Found");
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(mLocation!=null) {
try {
Double lat = mLocation.getLatitude();
Double lng = mLocation.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("My Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12));
} catch (Exception ex) {
Log.e("Location Error:","Exception was "+ex);
}
}
}
#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
// 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, 400, 1, this);
}
#Override
public void onLocationChanged(Location location) {
mMap.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(), location.getLongitude())).title("My Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(),"Please enable your location",Toast.LENGTH_LONG).show();
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
}
Now, the issue is that most of the times on I don't get any location, A map is shown without any marker and in the logs "Location Status:Location Not Found" which is set to be shown if location is null.
I tried to rebuild and run again. Now the location is detected on one device but it's showing the same awkward output on other devices. I want this to work every time but it's acting strange as the same code is showing two different behaviors on same device on different times with same settings.
P.S. Location is enabled on devices.
Any kind of help or tip will be appreciated. Thanks!
Try this code coded by me
Some time GPS can't able to locate your location that's why you getting null in object of mLocation
So my suggestion is to get location on bases of NETWORK_PROVIDER and also GPS_PROVIDER
here is my code
public class MapsActivity extends FragmentActivity implements LocationListener, OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
Location mLocation;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
#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);
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isGPSEnabled) {
mLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation == null) {
mLocation = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (locationManager != null) {
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;
}
if (mLocation != null) {
Log.e("Location Status: ", "Location Found");
} else {
Log.e("Location Status: ", "Location Not Found");
}
}
}
#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));*/
if (mLocation != null) {
try {
Double lat = mLocation.getLatitude();
Double lng = mLocation.getLongitude();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title("My Location"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 12.5f));
} catch (Exception ex) {
Log.e("Location Error:", "Exception was " + ex);
}
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "enable your location", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Please enable your location", Toast.LENGTH_LONG).show();
}
#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) {
return;
}
locationManager.removeUpdates(this);
}
}
I have an issue, I need to get the latitude and longitude of one specific moment like taking a picture. I get the Double values, the problem is that they're always 0. I receive no exceptions, and the coordinates are uploaded successfully to Firebase Database, but when I check them in the JSON, they are always zero (I took like 20 pictures).
This is my sections code of "location" stuffs and the uploading to Firebase Database.
My Main Activity is like this.
public class MainActivity extends AppCompatActivity implements LocationListener
Global variables related to Location
double latitude;
double longitude;
This goes inside onCreate():
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
String networkProvider = LocationManager.NETWORK_PROVIDER;
String gpsProvider = LocationManager.GPS_PROVIDER;
final Location location= new Location(networkProvider);
onLocationChanged(location);{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
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(gpsProvider, 5000, 10, this);
This goes in a button onClickListener(), also inside onCreate() method.
//Insert coordinates to JSON Firebase database...
Coordinates coordinates = new Coordinates();
coordinates.setLatitude(location.getLatitude());
coordinates.setLongitude(location.getLongitude());
testReference.push().setValue(coordinates);
Toast.makeText(MainActivity.this, "Coordinates uploaded!", Toast.LENGTH_LONG).show();
Also I have these methods inside MainActivity:
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
Try this:
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
String providerName = locationManager.getBestProvider(locationCritera,
true);
if(providerName!=null)
location = locationManager.getLastKnownLocation(providerName);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locationListener);
and Implement Your Location Listener class:
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
if (loc != null) {
location = loc;
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
check null value for getLastKnownLocation() method..