Getting extreme wrong location in LocationManager? - android

I get totally wrong location when using the LocationManager for a location. I get a Location about 500km faraway, the accuracy is around 588902. My Google Maps is showing the accurate position.
Does anyone have a idea about what the problem can be? It is the same when I use the getLastKnownLocation(). below is my code.
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
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;
}
Location myLocation = locationManager.getLastKnownLocation(provider);
//set map type
//mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
System.out.println("Lati >>> "+latitude + " Longi>>>>>>> "+longitude + " accuracy + = " + myLocation.getAccuracy());
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));

Related

Android GPS location problems

I have a problem with setting current location with GPS.
It works like it should(notification about finding location, then set it properly) on Android 5.0.1(Xiaomi Redmi Note 3)
But for example on Android 6.0 (Sony Xperia Z5 Compact) it doesn't work at all. No notification, GPS position set never. On Xperia I even don't have button on the right of map which is showed by line in code(mMap.setMyLocationEnabled(true);)
On Android 4.4.2(Gigabyte GsMart Roma R2plus) also no notification comes up, but I can see button of current location on right on top of screen. But still doesn't work like it should.
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = 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);
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
}
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
emailicek = user.getEmail();
emailicek = emailicek.replace(".", "");
mDatabase = FirebaseDatabase.getInstance().getReference();
if (latitude != 0) {
if (longitude != 0) {
mDatabase.child("userdata/" + email + "/latitude").setValue(latitude);
mDatabase.child("userdata/" + email + "/longitude").setValue(longitude);
}
}
LatLng latLng = new LatLng(latitude, longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
if (latitude != 0) {
mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
} else {
mMap.animateCamera(CameraUpdateFactory.zoomTo(1));
}
}
Did you make sure you requested the right permissions in the Manifest?
to get the last known location you'll need
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
for network based location, or:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
for GPS based location.
By the way there are a lot of good reasons why you should consider moving to Play Services to get your location, I strongly suggest you to read this:
Getting the Last Known Location - Android Developers

How to update my location when i move and it have to show you are in point 1 radius or not?

i tried this but its showing my current location first time i get information that i am inside or not . but when i moved outside of radius of point 1 its doesn't showing anything.
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//drawing marker
LatLng pointOne = new LatLng(23.10,72.50847684);
mMap.addMarker(new MarkerOptions().position(pointOne).title("Point 1"));
mMap.addMarker(new MarkerOptions().position(new LatLng(0,0)).title("Point 2").snippet("N"));
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);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
//myLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latitude = myLocation.getLatitude();
Log.e("latitude", String.valueOf(latitude));
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng pointTwo = new LatLng(latitude, longitude);
// Show the current location in Google Map
mMap.moveCamera(CameraUpdateFactory.newLatLng(pointTwo)); Log.e("location", String.valueOf(pointTwo));
//drawing overlay circle on marker
Circle circle = mMap.addCircle(new CircleOptions()
.center(pointOne)
.radius(5000)
.strokeColor(0x40FF0000)
.fillColor(0x35FF0000));
//for Checking marker is inside or not
float[] distance = new float[2];
Location.distanceBetween( pointTwo.latitude, pointTwo.longitude,
circle.getCenter().latitude, circle.getCenter().longitude, distance);
if( distance[0] > circle.getRadius() ){
Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
}
pointToPosition(pointOne);
}
Thanks for Help In advance
You can Use Google GeoFencing API to draw a virtual circle of some radius around the location.On user's entry/exit an event will be triggered which will help your cause.
Now getLastKnownLocation() which you are using May or May Not provide a location value. LocationManager maintains GPS location data until that data becomes outdate in like 8mins odd. After this, there will again be a cold startup and the GPS in your phone will try to get a fix and return results.
In case this is a cold startup, you can also get a NullPointerException because of the fact that the your last know location is outdated.
You can try a requestLocationUpdates() .... if lastKnownLocation returns a Null result...
This will cause the LocationManager to explicitly call the GPS in your phone to search for the current location... this will provide results in a callback function onLocationChanged... here you can get the current location....

I am getting the latitude and longitude as 0,0 [duplicate]

I am trying to get a device's location information using GPS, but for some reason one of the two coordinates is missing sometimes.
This is the code:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("LOCATION1", "Longitude: " + longitude);
Log.d("LOCATION2", "Latitude: " + latitude);
Sometimes I do get both coordinates, but not always, which makes me think about some kind of delay somewhere. Is there a way to find out why a GPS coordinate is missing when this happens?
Because the GPS isn't always on. getLastKnownLocation will return a location if it knows one and if it isn't too stale. Since nothing else was using the GPS, it doesn't know one. If you need a location, either requestLocationUpdates or requestSingleUpdate, which will turn on the GPS and get a new location.
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// mMap.addMarker(new MarkerOptions().position(sydney2).title("fi"));
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(locationManager.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
//
}
in onLocationChanged method you can use location.getLatitude & location.getLongitude

How to find out why GPS coordinates are missing in Android?

I am trying to get a device's location information using GPS, but for some reason one of the two coordinates is missing sometimes.
This is the code:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Log.d("LOCATION1", "Longitude: " + longitude);
Log.d("LOCATION2", "Latitude: " + latitude);
Sometimes I do get both coordinates, but not always, which makes me think about some kind of delay somewhere. Is there a way to find out why a GPS coordinate is missing when this happens?
Because the GPS isn't always on. getLastKnownLocation will return a location if it knows one and if it isn't too stale. Since nothing else was using the GPS, it doesn't know one. If you need a location, either requestLocationUpdates or requestSingleUpdate, which will turn on the GPS and get a new location.
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// mMap.addMarker(new MarkerOptions().position(sydney2).title("fi"));
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(locationManager.getBestProvider(criteria, true), 2000, 0, new android.location.LocationListener() {
#Override
public void onLocationChanged(Location location) {
//
}
in onLocationChanged method you can use location.getLatitude & location.getLongitude

When I switch on GPS or network provider new, my program doesn't get latitude and longitude

I have a program that gets latitude and longitude of the user.
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), 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.
}
Location myLocation = locationManager.getLastKnownLocation(provider);
Location myLocation = locationManager.getLastKnownLocation(provider);
boolean netEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (netEnabled) {
if (isGPSEnabled) {
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude()
} else if (!isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
// displayPromptForEnablingGPS(MapsActivity.this);
}
}
} else if (!netEnabled) {
if (isGPSEnabled) {
latitude = myLocation.getLatitude();
// Get longitude of the current location
longitude = myLocation.getLongitude();
} else {
// displayPromptForEnablingGPS(MapsActivity.this);
}
}
(displayPromptForEnablingGPS is for ACTION_LOCATION_SOURCE_SETTINGS)
In the program, if GPS and network providers are off, a window is opened for switching on them. When i switch GPS on in the first time, it gives error in first if(GPSEnabled) method(error on latitude=myLocation.getLatitude()). I can't get latitude and longitude. It is also same when i switch on only network provider. It gives "location" variable null. But if i open Google Maps, it starts to get latitude and longitude.
What can the problem be? It is problem of phone or i must make GPS run by writing any code?
Thanks for your help.
The method will return null value in case there’s no location information previously.
It’s better to get last known location iterate over all of the enabled providers, because this is the case that
there’s no GPS and Network provider. >> link on SO
It’s just better to add handling that case
if(!netEnabled && isGPSEnabled ){
//no network provider is enabled
Above sample code : here

Categories

Resources