This question already has an answer here:
android requestLocationUpdates failing
(1 answer)
Closed 2 years ago.
Is there a way to obtain information without displaying the map?
I want get my coordinate of my place during the work with other activity.
tnx a lot.
By Using LocationManager you can get lat and lang :
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
Using this code able to get latitude and Longitude values and make
sure before using application you got permission from manifest for accessing location
if(isGPS) {
Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
double lat=location.getLatitude();
double lng=location.getLongitude();
Toast.makeText(getApplicationContext(),lat+"and"+lng, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
display("GPS not Enabled");
}
Manifest permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Use this if you want to get lat lon without internet
LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLongitude();
longitude = location.getLatitude();
Related
I've got a activity that onCreate, it calculates the distance between your location and a event that is nearby, I've used lastKnownLocation to get the current device location and put a marker of it on a google map, but I need it to write the longitude and latitude outside of it's method to be used to calculate distances.
I've used LocationManager to get the rough coordinates but these aren't accurate enough and has a distance of 50 miles for something that's not even half a mile away. I currently have it so will overwrite longitude and latitude got from LocationManager but it does not.
I've attempted to use LocationRequest too and that hasn't helped.
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(60000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult){
if(locationRequest==null){
return;
}
for(Location location : locationResult.getLocations()) {
if (location != null){
userLat=location.getLatitude();
userLng=location.getLongitude();
}
}
}
};
LocationServices.getFusedLocationProviderClient(EventLocator.this).requestLocationUpdates(locationRequest,locationCallback, null);
LocationServices.getFusedLocationProviderClient(EventLocator.this).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location!=null){
double longitude=location.getLongitude();
double latitude=location.getLatitude();
userLng=longitude;
userLat=latitude;
}
}
});
All the permissions are correct, as I said I've used getLastLocation() to place a marker.
Make sure you added location permission in manifest file
If you are using android os 6 above make sure you have location permission
Make sure you GPS service is enabled in you mobile
public Location getLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastKnownLocationGPS != null) {
return lastKnownLocationGPS;
} else {
Location loc = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
System.out.println("1::"+loc);----getting null over here
System.out.println("2::"+loc.getLatitude());
return loc;
}
} else {
return null;
}
}
If still not working try to restart your phone and then try again.
You can create interface and implement it in the class where you need to calculate the distance
Usually GPS takes time to warm up. Your initial location reading could be from a cold GPS. In order to get a more accurate reading keep reading results until you get an accuracy reading that works for you.
Keep in mind GPS on a phone is not very accurate and would not be able to get accurate readings inside buildings or if not enough coverage is in your area at the time.
Last know position does not give you your current position, like it says it is the last know position which could have been more than a few minutes ago. Also it could've come from a cell tower reading instead of a GPS reading.
I'm using this code
lateinit var fusedLocationProviderClient: FusedLocationProviderClient
lateinit var latitude : Double
lateinit var longitude : Double
override fun onCreate() {
super.onCreate()
fusedLocationProviderClient = FusedLocationProviderClient(this)
updateLocationTracking()
}
#SuppressLint("MissingPermission")
private fun updateLocationTracking() {
if(PermissionUtility.isPermissionsGranted(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
val request = LocationRequest().apply {
interval = LOCATION_UPDATE_INTERVAL
fastestInterval = FASTEST_LOCATION_INTERVAL
priority = PRIORITY_HIGH_ACCURACY
}
fusedLocationProviderClient.requestLocationUpdates(
request,
locationCallback,
Looper.getMainLooper()
)
}
}
private val locationCallback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult?) {
super.onLocationResult(result)
result?.locations?.let { locations ->
for(location in locations) {
setLocationData(location)
}
}
}
}
private fun setLocationData(location : Location){
latitude = location.latitude
longitude = location.longitude
}
}
So I figured it out when I couldn't use my phone I use for debugging and used my personal phone for testing, went on the activity and the distances were correct.
Messed around with both debug phone settings and using GPS_PROVIDER and NETWORK_PROVIDER and when my phone used just GPS to get location, it got nothing. Other phone can, so think it's safe to say my debug phone's GPS is borked.
It's a old phone that, when I got a new one, I factory reset to use for debugging, as it helped with the backwards compatibility for older phones and smaller screens. I never thought if the actual hardware was faulty too after the reset.
So error was with the phone itself not the app. Guess it goes to show have two devices to test on.
I'm developing an Android app which achieve the position through NETWORK_PROVIDER, but I have problems on executing it on Android 7 (while it correctly works on previous versions). This is the code:
LocationManager posM;
double latitude;
double longitude;
List<Address> addresses = null;
try {
posM = (LocationManager) getSystemService(LOCATION_SERVICE);
Location location = posM.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
Geocoder geocoder;
geocoder = new Geocoder(Activity1.this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
I don't know why it crashes on Android 7... Thank you for help
Because getLastKnownLocation returns null most of the time. The system generally doesn't know your location. Use requestLocationUpdates or requestSingleUpdate to turn on the location detection and get the actual location.
I've just had some issues for odd reasons with the CameraUpdateFactory.
So I incorporated this code in an onclickListener on the GpsButton on a navigation fragment:
if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
Log.d("Permission checked", "checkSelfPermission passed with no errors");
map.setMyLocationEnabled(true);
Log.d("Permission checked", "Location Layer implementation successful");
} else {
//Request the Permission
ActivityCompat.requestPermissions(mapFragment.getActivity(), new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
This basically enables the location to be displayed as a blue dot on the map only when the GPS button is pressed. This has been perfectly functional so far.
I also incorporated a method to move the camera to my current location:
public void locateMe() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE); // Getting LocationManager object from System Service LOCATION_SERVICE
Criteria criteria = new Criteria();// Creating a criteria object to retrieve provider
String provider = locationManager.getBestProvider(criteria, true);// Getting the name of the best provider
if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mapFragment.getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 2);
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude(); //Getting latitude of the current location
double longitude = location.getLongitude(); // Getting longitude of the current location
myPosition = new LatLng(latitude, longitude); // Creating a LatLng object for the current location
map.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, CAMPUS_DEFAULT_ZOOM_LEVEL));//Camera Update method
}
}
For some reason, this is hit or miss. 3 days ago, it was locking on a position that wasn't where I currently was located while for the past 2 days it worked perfectly. No code was changed whatsoever. Could someone please explain what's going on? Any fixes or suggestions would be appreciated.
This occurs because you are using getLastKnownLocation.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.
If the provider is currently disabled, null is returned.
documentation
You have to use requestLocation updates if you want to retrieve the user's current documentation.
requestLocationUpdates documentation
I try to get my current location. First I created LocationListener:
public LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
myLocation = new LatLng(latitude, longitude);
}
};
The in onCreate method I try to cal requestLocatonUpates on LocationManager:
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,500f,mLocationListener);
But I get an error:
Cannot resolve method requestLocationUpdates(java.langString, long, float,com.google.android.gms.location.LocationListener)
requestLocationUpdates is a method provided in FusedLocationAPi. You should use LocationServices.FusedLocationApi.requestLocationUpdates method.
So you have to create a googleApiClient and a location request.
You can found it here : https://developer.android.com/training/location/index.html.
I am getting a null location when setting the longitutde and lattitude. I am not sure what I am doing wrong. I debugged this code with Location Services turned on and off. When they were on, the GPS_PROVIDER if statement would be true, and when they were off it neither of the conditions would be true and it would go to the else statement. However even when it confirmed the provider was enabled, the call to getLastKnownLocation returned null. Any ideas as to why?
private void setCoordinates(Context context) {
LocationManager lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Location location = null;
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
} else {
Log.e("AlarmLocation", "unable to get location");
}