I haven't used location services in a long, long time, so I'm just looking at the documentation for 'LocationRequest.Builder` and guessing at your equivalent code because it looks self-explanatory. Builders are a common pattern, used more often in Java-based APIs like this one than they are used in pure-Kotlin APIs. You can look up "java builder pattern" to read about it.

private fun NewLocation() { 
    val locationRequest = LocationRequest.Builder()
        .setPriority(Priority.PRIORITY_HIGH_ACCURACY)
        .setIntervalMillis(0L)
        .setMinUpdateIntervalMillis(0L)
        .setMaxUpdates(1)
        .build()
    mfusedlocation = LocationServices.getFusedLocationProviderClient(this)
    mfusedlocation.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
}

FYI since you're working on a portfolio:

  • Function names in Kotlin start with a verb and lower-case letter by convention. Or if it returns a modified copy of an object, you can use a past participle instead of a phrase starting with a verb. For example, I would rename NewLocation() to something like beginLocationRequest().

  • The mSomething pattern of naming variables (putting abbreviations in front of variable names) is called Hungarian notation. m stands for "member", but Kotlin properties are not even called member variables. I've never seen Hungarian notation used in Kotlin before, and it is rarely used in Java. It is widely regarded as making code less readable, especially with modern IDEs. I would advise against using it in a portfolio project as it is more likely to damage the impression you want to give than it is to help, especially if you are using it inconsistently.

Answer from Tenfour04 on Stack Overflow
🌐
Google
developers.google.com › google play services › locationrequest.builder
LocationRequest.Builder | Google Play services | Google for Developers
LocationRequest.Builder is used to construct a LocationRequest object · It includes constants for implicit maximum update age and minimum update interval, both set to be the same as the interval
🌐
Android Developers
developer.android.com › api reference › locationrequest.builder
LocationRequest.Builder | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Medium
medium.com › @psarakisnick › android-location-manager-with-kotlin-flows-082c992d1b31
Android location manager with Kotlin flows | by Nick Psarakis | Medium
January 21, 2024 - class LocationManagerImpl( private val context: Context ) : LocationManager { private val client: FusedLocationProviderClient by lazy { LocationServices.getFusedLocationProviderClient(context) } @SuppressLint("MissingPermission") @Throws override fun listenToLocation(): Flow<Location> { val request = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000L) .setMinUpdateDistanceMeters(1000F) .build() return callbackFlow { if (!hasLocationPermission()) throw NoPermissionsException val locationCallback = object : LocationCallback() { override fun onLocationResult(result: LocationResult) {
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › android.locations.locationrequest.builder
LocationRequest.Builder Class (Android.Locations) | Microsoft Learn
[<Android.Runtime.Register("android/location/LocationRequest$Builder", ApiSince=31, DoNotGenerateAcw=true)>] type LocationRequest.Builder = class inherit Object
🌐
DEV Community
dev.to › olubunmialegbeleye › location-services-the-android-14-maybe-15-too-way-4171
Location Services- the Android 14 (maybe 15 too) way - DEV Community
July 16, 2024 - private fun checkPhoneLocationSettings( activity: Activity, locationSettingsResult: ActivityResultLauncher<IntentSenderRequest>, callback: (Boolean) -> Unit ) { val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest) val client = LocationServices.getSettingsClient(activity) val task = client.checkLocationSettings(builder.build()) task.addOnSuccessListener { callback(true) } task.addOnFailureListener { exception -> if (exception is ResolvableApiException) { try { locationSettingsResult.launch( IntentSenderRequest.Builder(exception.resolution).build() ) } catch (sendEx: IntentSender.SendIntentException) { // Ignore the error.
Top answer
1 of 1
1

I haven't used location services in a long, long time, so I'm just looking at the documentation for 'LocationRequest.Builder` and guessing at your equivalent code because it looks self-explanatory. Builders are a common pattern, used more often in Java-based APIs like this one than they are used in pure-Kotlin APIs. You can look up "java builder pattern" to read about it.

private fun NewLocation() { 
    val locationRequest = LocationRequest.Builder()
        .setPriority(Priority.PRIORITY_HIGH_ACCURACY)
        .setIntervalMillis(0L)
        .setMinUpdateIntervalMillis(0L)
        .setMaxUpdates(1)
        .build()
    mfusedlocation = LocationServices.getFusedLocationProviderClient(this)
    mfusedlocation.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
}

FYI since you're working on a portfolio:

  • Function names in Kotlin start with a verb and lower-case letter by convention. Or if it returns a modified copy of an object, you can use a past participle instead of a phrase starting with a verb. For example, I would rename NewLocation() to something like beginLocationRequest().

  • The mSomething pattern of naming variables (putting abbreviations in front of variable names) is called Hungarian notation. m stands for "member", but Kotlin properties are not even called member variables. I've never seen Hungarian notation used in Kotlin before, and it is rarely used in Java. It is widely regarded as making code less readable, especially with modern IDEs. I would advise against using it in a portfolio project as it is more likely to damage the impression you want to give than it is to help, especially if you are using it inconsistently.

🌐
Codepath
guides.codepath.org › android › Retrieving-Location-with-LocationServices-API
Retrieving Location with LocationServices API | Android Development | CodePath Guides
mLocationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, UPDATE_INTERVAL) .setMinUpdateIntervalMillis(FASTEST_INTERVAL) .build(); // Create LocationSettingsRequest object using location request LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); ...
🌐
Medium
tomas-repcik.medium.com › locationrequest-create-got-deprecated-how-to-fix-it-e4f814138764
LocationRequest.create() got deprecated. How to fix it? | by Tomáš Repčík | Medium
October 30, 2022 - Fields of LocationRequest used to be filled upon the creation of the LocationRequest. However, new setters are used by the new Builder of the LocationRequest.
Find elsewhere
🌐
Kotlin Codes
kotlincodes.com › home › blog › locationlistener with kotlin
LocationListener With Kotlin - Kotlin Codes
May 15, 2025 - protected fun startLocationUpdates() { // Create the location request to start receiving updates mLocationRequest = LocationRequest() mLocationRequest!!.priority = LocationRequest.PRIORITY_HIGH_ACCURACY mLocationRequest!!.setInterval(INTERVAL) mLocationRequest!!.setFastestInterval(FASTEST_INTERVAL) // Create LocationSettingsRequest object using location request val builder = LocationSettingsRequest.Builder() builder.addLocationRequest(mLocationRequest!!) val locationSettingsRequest = builder.build() val settingsClient = LocationServices.getSettingsClient(this) settingsClient.checkLocationSetti
🌐
Android Developers
developer.android.com › api reference › locationrequest
LocationRequest | API reference | Android Developers
Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Stackademic
blog.stackademic.com › android-location-gps-explained-d9b04dac79cd
Android Location & GPS Explained. Learn how to use GPS on Android for… | by Michal Ankiersztajn | Stackademic
February 29, 2024 - val request = LocationRequest.Builder( /* Priority */ Priority.PRIORITY_HIGH_ACCURACY, /* intervalMillis */ 100 ).build() If you need more advanced settings then the interval and priority you need to set them before calling build method ·
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Google
codelabs.developers.google.com › codelabs › while-in-use-location
Receive location updates in Android with Kotlin | Google Codelabs
March 27, 2026 - In the base module, search for TODO: Step 1.3, Create a LocationRequest in the ForegroundOnlyLocationService.kt file.
🌐
GitHub
gist.github.com › arkilis › 7aef93cd50cf372d3a7c3ed5391e8fbf
Get location from google map on kotlin · GitHub
Get location from google map on kotlin. GitHub Gist: instantly share code, notes, and snippets.
🌐
GitHub
gist.github.com › shihabmi7 › fa6389bb94f407d8b6d768e39588a617
Location Updates in Kotlin · GitHub
Location Updates in Kotlin. GitHub Gist: instantly share code, notes, and snippets.
🌐
Finotes Blog
blog.finotes.com › post › efficient-ways-of-using-location-services-in-kotlin-android-apps
Efficient Ways of Using Location Services in Kotlin Android Apps
July 4, 2023 - Here's an example: private val locationRequest: LocationRequest = LocationRequest.create().apply { interval = 10000 // Update interval in milliseconds fastestInterval = 5000 // Fastest update interval in milliseconds priority = LocationRequ...
Top answer
1 of 8
56

In 2019 Best Offical Solution in Kotlin

Google API Client/FusedLocationApi are deprecated and Location Manager is not useful at all. So Google prefer Fused Location Provider Using the Google Play services location APIs "FusedLocationProviderClient" is used to get location and its better way for battery saving and accuracy

Here is sample code in kotlin to get the last known location /one-time location( equivalent to the current location)

 // declare a global variable of FusedLocationProviderClient
    private lateinit var fusedLocationClient: FusedLocationProviderClient

// in onCreate() initialize FusedLocationProviderClient
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)

 /**
     * call this method for receive location
     * get location and give callback when successfully retrieve
     * function itself check location permission before access related methods
     *
     */
    fun getLastKnownLocation() {
            fusedLocationClient.lastLocation
                .addOnSuccessListener { location->
                    if (location != null) {
                       // use your location object
                        // get latitude , longitude and other info from this
                    }

                }

    }

If your app can continuously track the location then you have to receive Receive location updates

Check the sample for that in kotlin

// declare a global variable FusedLocationProviderClient
        private lateinit var fusedLocationClient: FusedLocationProviderClient

    // in onCreate() initialize FusedLocationProviderClient
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)


      // globally declare LocationRequest
        private lateinit var locationRequest: LocationRequest

        // globally declare LocationCallback    
        private lateinit var locationCallback: LocationCallback


        /**
         * call this method in onCreate
         * onLocationResult call when location is changed 
         */
        private fun getLocationUpdates()
        {

                fusedLocationClient = LocationServices.getFusedLocationProviderClient(context!!)
                locationRequest = LocationRequest()
                locationRequest.interval = 50000
                locationRequest.fastestInterval = 50000
                locationRequest.smallestDisplacement = 170f // 170 m = 0.1 mile
                locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //set according to your app function
                locationCallback = object : LocationCallback() {
                    override fun onLocationResult(locationResult: LocationResult?) {
                        locationResult ?: return

                        if (locationResult.locations.isNotEmpty()) {
                            // get latest location 
                            val location =
                                locationResult.lastLocation
                            // use your location object
                            // get latitude , longitude and other info from this
                        }


                    }
                }
        }

        //start location updates
        private fun startLocationUpdates() {
            fusedLocationClient.requestLocationUpdates(
                locationRequest,
                locationCallback,
                null /* Looper */
            )
        }

        // stop location updates
        private fun stopLocationUpdates() {
            fusedLocationClient.removeLocationUpdates(locationCallback)
        }

        // stop receiving location update when activity not visible/foreground
        override fun onPause() {
            super.onPause()
            stopLocationUpdates()
        }

        // start receiving location update when activity  visible/foreground
        override fun onResume() {
            super.onResume()
            startLocationUpdates()
        }

Make sure you take care about Mainfaist permission and runtime permission for location

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

and for Gradle add this

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

For more details follow these official documents

https://developer.android.com/training/location/retrieve-current

https://developer.android.com/training/location/receive-location-updates

https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderClient

2 of 8
32

When GetUserLocation returns, locationManager goes out of scope and presumably is destroyed, preventing onLocationChanged from being called and providing updates.

Also, you've defined mylocation inside of GetUserLocation so it also goes out of scope and further kills any chance or your getting an update.

You have not shown where and how the outer mylocation is declared (outside of GetUserLocation), but how ever it is declared, it is being shadowed by the one inside of GetUserLocation. So you aren't getting much.

Here is an example of how you might do it. (The variable thetext is defined within the layout xml and accessed with Kotlin extensions.)

// in the android manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
// allow these through Appliation Manager if necessary

// inside a basic activity
private var locationManager : LocationManager? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    // Create persistent LocationManager reference
    locationManager = getSystemService(LOCATION_SERVICE) as LocationManager?

    fab.setOnClickListener { view ->
        try {
            // Request location updates
            locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListener)
        } catch(ex: SecurityException) {
            Log.d("myTag", "Security Exception, no location available")
        }
    }
}

//define the listener
private val locationListener: LocationListener = object : LocationListener {
    override fun onLocationChanged(location: Location) {
        thetext.text = ("" + location.longitude + ":" + location.latitude)
    }
    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
    override fun onProviderEnabled(provider: String) {}
    override fun onProviderDisabled(provider: String) {}
}