-1

I'm writing an Android application that uses Google Maps, now my goal as a start is to request location permissions from the user, and then retrieve his coordinates, according to Google searches I found the following option:

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = location -> {
    lat = location.getLatitude();
    lon = location.getLongitude();
};

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,1,locationListener);
}

System.out.println("lon + lat"+ lat + " " + lon);

The problem is that it doesn't go into the locationListener function. I tried to print the result of Latitude and Longitude and i got 0.0,0.0.

Latitude and Longitude , and I got 0.0

Elikill58
  • 4,050
  • 24
  • 23
  • 45
  • try this https://stackoverflow.com/questions/17519198/how-to-get-the-current-location-latitude-and-longitude-in-android – Dhruv Sakariya Dec 16 '22 at 10:22
  • `The problem is that it doesn't go into the locationListener function.` Yes, and why doesnt it do so? Tell your real problem! – blackapps Dec 16 '22 at 10:43

1 Answers1

0

Add dependency in gradle.app

implementation 'com.google.android.gms:play-services-location:21.0.1'

Kotlin

You can get user's current location by using FusedLocationProviderClient as follow

private lateinit var fusedLocationClient: FusedLocationProviderClient

In your onCreate() method

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.id.activity_main)

    // Initialize object
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
    getCurrentLocation()
}

Last location returns the most recent historical location currently available.

private fun getCurrentLocation() {
    // Checking Location Permission
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        resultLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
        return
    }
    fusedLocationClient.getLastLocation().addOnSuccessListener(this, OnSuccessListener { location: Location? ->
        if (location != null) {
            val lat = location.latitude
            val lon = location.longitude
        }
    })
}

private val resultLauncher = registerForActivityResult<String, Boolean>(RequestPermission()) { isGranted: Boolean ->
    if (isGranted) {
        getCurrentLocation()
    } else {
        Toast.makeText(this, "Location permission not granted", Toast.LENGTH_SHORT).show()
    }
}

Java

private FusedLocationProviderClient fusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState)
    setContentView(R.id.activity_main)

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    getCurrentLocation();
}

private void getCurrentLocation() {
    // Checking Location Permission
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        resultLauncher.launch(android.Manifest.permission.ACCESS_FINE_LOCATION);
        return;
    }

    fusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> {
        if (location != null) {
            double lat = location.getLatitude();
            double lon = location.getLongitude();
        }
    });
}

Use the resultLauncher object to request location permission.

private final ActivityResultLauncher<String> resultLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
    if (isGranted) {
        getCurrentLocation();
    } else {
        Toast.makeText(this, "Location permission not granted", Toast.LENGTH_SHORT).show();
    }
});
Sohaib Ahmed
  • 1,990
  • 1
  • 5
  • 23
  • Just to make sure,my code is Java language – נתנאל חבס Dec 16 '22 at 10:54
  • Ooh sorry, I'll update it – Sohaib Ahmed Dec 16 '22 at 11:19
  • I have added in java, you can see now – Sohaib Ahmed Dec 16 '22 at 11:26
  • when i declare on private FusedLocationProviderClient its dosent said to import the class, its ask me to create the class, what i need to do to solve it? – נתנאל חבס Dec 16 '22 at 11:53
  • It seems like, you are missing a dependency.. Add this, implementation 'com.google.android.gms:play-services-location:21.0.1' in gradle.app. – Sohaib Ahmed Dec 16 '22 at 11:59
  • Oh ok, and what i need to enter to OnSuccessListener or just to copy paste the func? – נתנאל חבס Dec 16 '22 at 12:11
  • copy/paste it. It will do the work – Sohaib Ahmed Dec 16 '22 at 12:13
  • I have update it again, made it more easy without OnSuccessListener, you can try now – Sohaib Ahmed Dec 16 '22 at 12:20
  • its not working,i tried this before and after that your func if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 101); } – נתנאל חבס Dec 16 '22 at 12:31
  • Copy & paste this, 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; } fusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> { if (location != null) { double lat = location.getLatitude(); double lon = location.getLongitude(); } }); – Sohaib Ahmed Dec 16 '22 at 12:33
  • if i delete all the func that i wrote and paste yours, it dosent pop up request for location, anyway it inter to the if statement(of the return;). there is a way that i can talk with in private(discord?that i can show you the exac problem and help me on real time?) – נתנאל חבס Dec 16 '22 at 12:41
  • No, you don't need to remove the code for asking permission.. My Code will execute once permission if permission is allowed. For testing, you can allow permission from app settings and check if you get the location or not. After that, we can figure out the flow of asking permission. Note: Turn on your GPS as well before testing. – Sohaib Ahmed Dec 16 '22 at 12:57
  • ok its working if do it menual,i mean if i enter to the settings and allow the location all the time, i got the numbers,now we just need to understand what is not right – נתנאל חבס Dec 16 '22 at 13:13
  • ok i tested that,i added again the if statement (with FINE.LOCATION && COARSE_LOCATION) and after that your func,at the first time that i install the app its ask me for allow the location, but didnt enter to the func the gives you lon,lat just on the second time that enter to the app – נתנאל חבס Dec 16 '22 at 13:17
  • i also check the strange thing: i have to private double lat,lon. and when i print the lat and lon in your fucn(on the second time like i said above one comment),its give me the numbers, but if i print that after that passing the func it will again 0.0 – נתנאל חבס Dec 16 '22 at 13:38
  • I have updated the answer, firstly you will check for the permission, if its already granted, it will show the results. Secondly, if permission is required, it will request for permission and in its result, we will be checking again if not granted it will show a toast. Otherwise it will call the same function again and now this time, you get the location updates automatically.. You can just copy/paste and import libraries – Sohaib Ahmed Dec 17 '22 at 04:22