FusedLocations doesn't send location updates when map.isMyLocationEnabled = false. Strange behaviour - android

I want to add a custom image as the my location indicator.
The only way to hide the blue dot is to setIsMyLocationEnabled = false. Doing this somehow also disables the updates from FusedLocation. I want to know if this is intended or its just a bug?
Gradle -
implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
Activity (unnecessary code removed)-
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var mMap: GoogleMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
startLocationUpdate()
mapFragment.getMapAsync(this)
}
private var marker: Marker? = null
private var lastLocation: Location? = null
override fun onMapReady(googleMap: GoogleMap) {
mMap = googleMap
val sydney = LatLng(-34.0, 151.0)
val icon = BitmapDescriptorFactory.fromResource(R.drawable.ic_location_indicator)
val location = lastLocation?.let { LatLng(it.latitude, it.longitude) } ?: sydney
val markerOpts = MarkerOptions().position(location).flat(true).anchor(0.5f, 0.5f)
.icon(icon)
marker = mMap.addMarker(markerOpts)
val cameraPosition = CameraPosition.builder().zoom(17f).target(location).build()
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
mMap.isMyLocationEnabled = false // disabling MyLocation here stops FusedLocation updates
mMap.uiSettings.isMyLocationButtonEnabled = true
}
fun startLocationUpdate() {
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
lastLocation = location
}
val locationRequest = LocationRequest()
locationRequest.fastestInterval = 1000
locationRequest.smallestDisplacement = 0f
fusedLocationClient.requestLocationUpdates(locationRequest, object :
LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
// Never gets called when mMap.isMyLocationEnabled = false but works properly
// if mMap.isMyLocationEnabled = true.
marker?.position = LatLng(p0.lastLocation.latitude, p0.lastLocation.longitude)
val cameraPosition = CameraPosition.builder().target(latlng).zoom(17f).build()
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition))
}
}, Looper.getMainLooper())
}
}
Layout-
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.temp.MapsActivity" />

The problem was with the location request. The LocationRequest by default has a low priority so it wont update very often.
When set mMap.isMyLocationEnabled = false it takes the default priority which is low. Just adding 2 lines solved the problem.
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationRequest.interval = 5000

Related

FusedLocationProviderClient not giving correct Location

I am using FusedLocationProviderClient to get the location but it not giving correct Location (i.e. precise). The location it provides is 20 blocks away atleast which is not really a good solution for me.
LatLng i Need : 28.602205, 77.380126
LatLng i receive: 28.600504,77.382864
Here is code for the same
val client = LocationServices.getFusedLocationProviderClient(this)
var locationRequest = LocationRequest.create().apply {
interval = TimeUnit.SECONDS.toMillis(20)
}
client.requestLocationUpdates(locationRequest, object: LocationCallback() {
override fun onLocationAvailability(p0: LocationAvailability) {
super.onLocationAvailability(p0)
}
override fun onLocationResult(p0: LocationResult) {
super.onLocationResult(p0)
var latLong = p0.lastLocation
marker.position = LatLng(latLong!!.latitude, latLong.longitude)
Log.d("sagar", "Location result: $p0")
}
}, Looper.getMainLooper())

Show multiple user`s location at the same time on a map (Kotlin, Firebase Realtime Database)

This question reflects back to a previous question: Show multiple registered user`s location on the same map (Android Studio, Firebase, Kotlin)
My main problem is that I have created a chatting app in Android Studio, and also added a map activity, using Google Api. I am using Firebase Realtime Database, and this is how my tree currently looks like:
I want the "userlocation" appear under each of my registered user, so all registered user`s location will will appear on my Google Map as a marker.
Here is my MapsActivity:
class MapsActivity : AppCompatActivity(), OnMapReadyCallback {
companion object {
var currentUser: User? = null
val TAG = "MapsActivity"
}
private lateinit var map: GoogleMap
private val LOCATION_PERMISSION_REQUEST = 1
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var locationRequest: LocationRequest
private lateinit var locationCallback: LocationCallback
private fun getLocationAccess() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
map.isMyLocationEnabled = true
getLocationUpdates()
startLocationUpdates()
}
else
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST)
}
private fun getLocationUpdates() {
locationRequest = LocationRequest()
locationRequest.interval = 30000
locationRequest.fastestInterval = 20000
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
if (locationResult.locations.isNotEmpty()) {
val location = locationResult.lastLocation
// val uid = FirebaseAuth.getInstance().currentUser?.uid
// val rootRef = FirebaseFirestore.getInstance()
// val usersRef = rootRef.collection("users")
// val uidRef = uid?.let { usersRef.document(it) }
// if (uidRef != null) {
// uidRef.get()
// .addOnSuccessListener { document ->
// if (document != null) {
// val latitude = document.getDouble("latitude")
// val longitude = document.getDouble("longitude")
// Log.d(TAG, ", " + location.latitude + location.longitude)
// } else {
// Log.d(TAG, "No such document")
// }
// }
// .addOnFailureListener { exception ->
// Log.d(TAG, "get failed with ", exception)
// }
// }
lateinit var databaseRef: DatabaseReference
databaseRef = Firebase.database.reference
val locationlogging = LocationLogging(location.latitude, location.longitude)
databaseRef.child("/userlocation").setValue(locationlogging)
.addOnSuccessListener {
Toast.makeText(applicationContext, "Locations written into the database", Toast.LENGTH_LONG).show()
}
.addOnFailureListener {
Toast.makeText(applicationContext, "Error occured while writing your location to the database", Toast.LENGTH_LONG).show()
}
}
}
}
}
#SuppressLint("MissingPermission")
private fun startLocationUpdates() {
fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback, null)
}
#SuppressLint("MissingPermission")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == LOCATION_PERMISSION_REQUEST) {
if (grantResults.contains(PackageManager.PERMISSION_GRANTED)) {
map.isMyLocationEnabled = true
} else { Toast.makeText(this, "User has not granted location access permission", Toast.LENGTH_LONG).show()
finish()
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_maps)
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
val mapFragment = supportFragmentManager
.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
getLocationAccess()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.nav_menu_map, menu)
return super.onCreateOptionsMenu(menu)
}
I commented out some of the codes as I wasn`t able to implement it properly. When I ran the code, the latitude and longitude appeared in my Logcat, but in my Realtime database, it wiped out all my data under /users and it was replaced by the latitude and longitude.
Here is my LocationLogging:
import com.google.firebase.database.IgnoreExtraProperties
#IgnoreExtraProperties
data class LocationLogging(
var Latitude: Double? = 0.0,
var Longitude: Double? = 0.0
)
I am looking to find an easy way, which puts the coordinates into my Firebase Realtime Database under each of my registered users, and show all locations on the map at the same time.
You can get the current user with the firebase auth SDK and change the path where you save the data to save it under the user path. You would need to change this part of your code:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
lateinit var databaseRef: DatabaseReference
databaseRef = Firebase.database.reference
val locationlogging = LocationLogging(location.latitude, location.longitude)
databaseRef.child("users").child(user.getUid()).child("userlocation").setValue(locationlogging)
.addOnSuccessListener {
Toast.makeText(applicationContext, "Locations written into the database", Toast.LENGTH_LONG).show()
}
.addOnFailureListener {
Toast.makeText(applicationContext, "Error occured while writing your location to the database", Toast.LENGTH_LONG).show()
}

ViewModel not updating with data change

So, this is my first time using architecture components in Android. I'm trying to create a ViewModel that will keep returning the latest location which can be used by UI elements. I've created a viewModel like this:
class LocationViewModel(application: Application) : AndroidViewModel(application) {
val currentLocation = MutableLiveData<Location?>()
init {
val ctx = getApplication<Application>().applicationContext
val fusedLocationProvider = LocationServices.getFusedLocationProviderClient(ctx)
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
locationRequest.interval = 5000
locationRequest.fastestInterval = 2000
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
val client = LocationServices.getSettingsClient(ctx)
client.checkLocationSettings(builder.build()).addOnFailureListener {
currentLocation.postValue(null)
}
val locationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
super.onLocationResult(p0)
p0 ?: return
currentLocation.postValue(p0.lastLocation)
}
}
fusedLocationProvider.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
}
}
And I observe this ViewModel in an activity, like so
class MainActivity : AppCompatActivity() {
private lateinit var locationText: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
locationText = findViewById(R.id.locationText)
val location = ViewModelProviders.of(this)[LocationViewModel::class.java]
location.currentLocation.observe(this, Observer { resutlLocation: Location? ->
locationText.text =
if (resutlLocation != null) "Lat: ${resutlLocation.latitude} Long: ${resutlLocation.longitude}" else "Null"
})
}
}
The TextView doesn't even gets updated once. How things like these should be done? What Am I doing wrong?
In View View model create function like this.
fun initdata() {
val ctx = getApplication<Application>().applicationContext
val fusedLocationProvider = LocationServices.getFusedLocationProviderClient(ctx)
val locationRequest = LocationRequest.create()
locationRequest.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
locationRequest.interval = 5000
locationRequest.fastestInterval = 2000
val builder = LocationSettingsRequest.Builder().addLocationRequest(locationRequest)
val client = LocationServices.getSettingsClient(ctx)
client.checkLocationSettings(builder.build()).addOnFailureListener {
currentLocation.postValue(null)
}
val locationCallback = object : LocationCallback() {
override fun onLocationResult(p0: LocationResult?) {
super.onLocationResult(p0)
p0 ?: return
currentLocation.postValue(p0.lastLocation)
}
}
fusedLocationProvider.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
)
}
then use like this
val viewModel = ViewModelProviders.of(this)[LocationViewModel::class.java]
viewModel.initdata()
Edit 1
You can lazy initialize like this way
private val users:MutableLiveData<Location?> by lazy {
MutableLiveData().also {
initdata()
}
}
more details refer ViewModel

Place tap listener on Google maps android

I have an android app with a map fragment.
The map displays places and I am looking for a way to add a listener to get that place when the user taps on them.
The most relevant information I found was a suggestion to add a listener for clicks to the map, get the long&lat and then search for a place based on that.
I thought I could do that using FetchPlaceRequest but this also seems to require a placeId in the first place when instantiating.
Am I missing something really basic?
EDIT
The code for the fragment containing the map (I thought implementing PlaceSelectionlistener would do the work)
class MapFragment : Fragment(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener,
PlaceSelectionListener, KoinComponent {
private lateinit var mapViewModel: MapViewModel
private lateinit var map: GoogleMap
private var fusedLocationClient: FusedLocationProviderClient? = null
private var locationRequest: LocationRequest? = null
private var locationCallback: LocationCallback? = null
private val permissionsUtils : PermissionsUtils by inject()
private val preferencesUtils : PreferencesUtils by inject { parametersOf(activity!!.applicationContext)}
private var root : View? = null
private val defaultZoom : Float = 16f
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mapViewModel = ViewModelProviders.of(this).get(MapViewModel::class.java)
root = inflater.inflate(R.layout.fragment_map, container, false)
if (canAccessLocation()) {
initialiseMap(true)
} else {
val permissions = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
requestPermissions(permissions, PermissionRequests.FineLocation.value)
}
return root
}
override fun onMarkerClick(p0: Marker?) = false
override fun onMapReady(googleMap: GoogleMap) {
map = googleMap
map.setMapStyle(MapStyleOptions
.loadRawResourceStyle(activity!!.applicationContext, preferencesUtils.mapMode))
map.uiSettings.isZoomControlsEnabled = true
if (canAccessLocation()){
map.isMyLocationEnabled = true
map.uiSettings.isMyLocationButtonEnabled = true
}
map.setOnMarkerClickListener(this)
}
override fun onRequestPermissionsResult(requestCode: Int,
permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PermissionRequests.FineLocation.value -> {
val permissionGranted = grantResults.isNotEmpty()
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
initialiseMap(permissionGranted)
}
}
}
override fun onPause() {
super.onPause()
fusedLocationClient?.removeLocationUpdates(locationCallback)
}
override fun onResume() {
super.onResume()
requestLocationUpdates()
}
override fun onPlaceSelected(status: Place) {
val toast = Toast.makeText(activity!!.applicationContext,""+ status!!.name + status!!.latLng, Toast.LENGTH_LONG)
toast.setGravity(Gravity.TOP, 0, 0)
toast.show()
}
override fun onError(status: Status) {
Toast.makeText(activity!!.applicationContext,"" + status.toString(), Toast.LENGTH_LONG)
.show()
}
private fun initialiseMap(withLocation: Boolean) {
val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)
if (!withLocation) {
return
}
requestLocationUpdates()
}
private fun requestLocationUpdates() {
if (fusedLocationClient == null) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity!!.applicationContext)
}
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
val locationList = locationResult.locations
if (locationList.size > 0) {
val location = locationList[locationList.size - 1]
val latLng = LatLng(location.latitude, location.longitude)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, defaultZoom))
}
}
}
fusedLocationClient?.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper())
locationRequest = LocationRequest()
locationRequest?.interval = 1800000
locationRequest?.fastestInterval = 1800000
locationRequest?.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY
fusedLocationClient?.lastLocation?.addOnCompleteListener(Activity()) { task ->
if (task.isSuccessful && task.result != null) {
val latLong = LatLng(task.result!!.latitude, task.result!!.longitude)
map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLong, defaultZoom))
}
}
}
private fun canAccessLocation(): Boolean {
return permissionsUtils.hasPermission(activity!!.applicationContext, Manifest.permission.ACCESS_FINE_LOCATION)
}
}
Because you can't manage places that shown on MapView (MapFragment) and it's markers not clickable (and customizable) IMHO better way is to hide "default" place markers via Google Maps styling like in this answer of Jozef:
Create JSON file src\main\res\raw\map_style.json like this:
[
{
featureType: "poi",
elementType: "labels",
stylers: [
{
visibility: "off"
}
]
}
]
Add map style to your GoogleMap
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(getContext(), R.raw.map_style));
and then - get nearby places via Place Search from Google Places API URL request:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=<LAT_LNG>&types=point_of_interest&radius=<RADIUS_IN_METERS>&sensor=false&key=<YOUR_APP_KEY>
parse it and show desired places on map programmatically as customizable and clickable Google Maps markers. That approach allows to you not only process marker clicks via default onMarkerClick(), but to manage quantity and types of places, marker icons design etc. There is also no need to create a request and process its response every time a user clicks on map.
NB! Nearby URL request returns only 20 places, for load more data you should use string value from next_page_token tag of response and pass it via pagetoken parameter for next request:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=<LAT_LNG>&types=point_of_interest&radius=<RADIUS_IN_METERS>&sensor=false&key=<YOUR_APP_KEY>&pagetoken=<TOKEN_FOR_NEXT_PAGE_FROM_next_page_token_TAG_OF_RESPONSE>

Get location android Kotlin

I recently added get location function. When I try to show longitude and latitude, it returns zero.
This my LocationListener class:
inner class MylocationListener: LocationListener {
constructor():super(){
mylocation= Location("me")
mylocation!!.longitude
mylocation!!.latitude
}
override fun onLocationChanged(location: Location?) {
mylocation=location
}
override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {}
override fun onProviderEnabled(p0: String?) {}
override fun onProviderDisabled(p0: String?) {}
}
And this my GetUserLocation function:
fun GetUserLocation(){
var mylocation= MylocationListener()
var locationManager=getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0.1f,mylocation)
}
And this my function to return my longitude and latitude:
fun getLoction (view: View){
prgDialog!!.show();
GetUserLocation()
button.setTextColor(getResources().getColor(R.color.green));
textView.text = mylocation!!.latitude.toFloat().toString()
Toast.makeText(this, mylocation!!.latitude.toFloat().toString(), Toast.LENGTH_LONG).show()
Toast.makeText(this, mylocation!!.longitude.toFloat().toString(), Toast.LENGTH_LONG).show()
prgDialog!!.hide()
}
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
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) {}
}
I know it's late, but now Google has made it simpler to use. In the developer site, it says that you need to create a Client:
private lateinit var fusedLocationClient: FusedLocationProviderClient
Then onCreate get the provider:
override fun onCreate(savedInstanceState: Bundle?) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
}
And finally, to get your last location just call:
//Don't forget to ask for permissions for ACCESS_COARSE_LOCATION
//and ACCESS_FINE_LOCATION
#SuppressLint("MissingPermission")
private fun obtieneLocalizacion(){
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
latitude = location?.latitude
longitude = location?.longitude
}
}
*Tested with this implementation for location (Setup in your app gradle file)
implementation 'com.google.android.gms:play-services-location:15.0.1'
For more info, check this link:
Obtain last location
Get location with address in android kotlin
Add this line in dependencies
implementation 'com.google.android.gms:play-services-location:17.0.0'
Add this in AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Copy this below code in your class
class MainActivity : AppCompatActivity() {
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var locationRequest: LocationRequest
private lateinit var locationCallback: LocationCallback
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
/*Check location*/
checkLocation()
}
private fun checkLocation(){
val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
showAlertLocation()
}
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
getLocationUpdates()
}
private fun showAlertLocation() {
val dialog = AlertDialog.Builder(this)
dialog.setMessage("Your location settings is set to Off, Please enable location to use this application")
dialog.setPositiveButton("Settings") { _, _ ->
val myIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(myIntent)
}
dialog.setNegativeButton("Cancel") { _, _ ->
finish()
}
dialog.setCancelable(false)
dialog.show()
}
private fun getLocationUpdates() {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
locationRequest = LocationRequest()
locationRequest.interval = 50000
locationRequest.fastestInterval = 50000
locationRequest.smallestDisplacement = 170f //170 m = 0.1 mile
locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY //according to your app
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
locationResult ?: return
if (locationResult.locations.isNotEmpty()) {
/*val location = locationResult.lastLocation
Log.e("location", location.toString())*/
val addresses: List<Address>?
val geoCoder = Geocoder(applicationContext, Locale.getDefault())
addresses = geoCoder.getFromLocation(
locationResult.lastLocation.latitude,
locationResult.lastLocation.longitude,
1
)
if (addresses != null && addresses.isNotEmpty()) {
val address: String = addresses[0].getAddressLine(0)
val city: String = addresses[0].locality
val state: String = addresses[0].adminArea
val country: String = addresses[0].countryName
val postalCode: String = addresses[0].postalCode
val knownName: String = addresses[0].featureName
Log.e("location", "$address $city $state $postalCode $country $knownName")
}
}
}
}
}
// 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()
}}
Run your code and check the log, Happy Coding
I read many of answers but question is get only last known location.
With receiver it continuously send latitude and longitude
I have solution for this in kotlin..
Give permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
public fun getLastKnownLocation(context: Context) {
val locationManager: LocationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val providers: List<String> = locationManager.getProviders(true)
var location: Location? = null
for (i in providers.size - 1 downTo 0) {
location= locationManager.getLastKnownLocation(providers[i])
if (location != null)
break
}
val gps = DoubleArray(2)
if (location != null) {
gps[0] = location.getLatitude()
gps[1] = location.getLongitude()
Log.e("gpsLat",gps[0].toString())
Log.e("gpsLong",gps[1].toString())
}
}
I would like to help someone who is trying to get location from scratch.
Here is the reference: Kotlin Get Current Location
Code will first check whether location is on or off in device and then will fetch latitude and longitudes and will update it constantly.
In build.gradle(Module:app) file put this
compile 'com.google.android.gms:play-services:11.8.0'
activity_main.xml code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Latitude:"
android:textSize="18sp" />
<TextView
android:id="#+id/latitude_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/latitude"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/latitude"
android:textSize="16sp" />
<TextView
android:id="#+id/longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Longitude:"
android:layout_marginTop="24dp"
android:textSize="18sp" />
<TextView
android:id="#+id/longitude_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/longitude"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/longitude"
android:textSize="16sp"/>
</RelativeLayout>
MainActivity.kt
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.provider.Settings
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.model.LatLng
class MainActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private var mLatitudeTextView: TextView? = null
private var mLongitudeTextView: TextView? = null
private var mGoogleApiClient: GoogleApiClient? = null
private var mLocation: Location? = null
private var mLocationManager: LocationManager? = null
private var mLocationRequest: LocationRequest? = null
private val listener: com.google.android.gms.location.LocationListener? = null
private val UPDATE_INTERVAL = (2 * 1000).toLong() /* 10 secs */
private val FASTEST_INTERVAL: Long = 2000 /* 2 sec */
private var locationManager: LocationManager? = null
private val isLocationEnabled: Boolean
get() {
locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mLatitudeTextView = findViewById(R.id.latitude_textview) as TextView
mLongitudeTextView = findViewById(R.id.longitude_textview) as TextView
mGoogleApiClient = GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build()
mLocationManager = this.getSystemService(Context.LOCATION_SERVICE) as LocationManager
Log.d("gggg","uooo");
checkLocation() //check whether location service is enable or not in your phone
}
#SuppressLint("MissingPermission")
override fun onConnected(p0: Bundle?) {
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
}
startLocationUpdates()
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient)
if (mLocation == null) {
startLocationUpdates()
}
if (mLocation != null) {
// mLatitudeTextView.setText(String.valueOf(mLocation.getLatitude()));
//mLongitudeTextView.setText(String.valueOf(mLocation.getLongitude()));
} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show()
}
}
override fun onConnectionSuspended(i: Int) {
Log.i(TAG, "Connection Suspended")
mGoogleApiClient!!.connect()
}
override fun onConnectionFailed(connectionResult: ConnectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode())
}
override fun onStart() {
super.onStart()
if (mGoogleApiClient != null) {
mGoogleApiClient!!.connect()
}
}
override fun onStop() {
super.onStop()
if (mGoogleApiClient!!.isConnected()) {
mGoogleApiClient!!.disconnect()
}
}
#SuppressLint("MissingPermission")
protected fun startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL)
// Request location updates
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
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this)
Log.d("reque", "--->>>>")
}
override fun onLocationChanged(location: Location) {
val msg = "Updated Location: " +
java.lang.Double.toString(location.latitude) + "," +
java.lang.Double.toString(location.longitude)
mLatitudeTextView!!.text = location.latitude.toString()
mLongitudeTextView!!.text = location.longitude.toString()
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
// You can now create a LatLng Object for use with maps
val latLng = LatLng(location.latitude, location.longitude)
}
private fun checkLocation(): Boolean {
if (!isLocationEnabled)
showAlert()
return isLocationEnabled
}
private fun showAlert() {
val dialog = AlertDialog.Builder(this)
dialog.setTitle("Enable Location")
.setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " + "use this app")
.setPositiveButton("Location Settings") { paramDialogInterface, paramInt ->
val myIntent = Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(myIntent)
}
.setNegativeButton("Cancel") { paramDialogInterface, paramInt -> }
dialog.show()
}
companion object {
private val TAG = "MainActivity"
}
}
gradle(Module: appname.app)
buildFeatures{
viewBinding true
} // for databinding
dependencies{
implementation 'com.google.android.gms:play-services-location:18.0.0'
}
manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
activity:
class Updateposition : AppCompatActivity() {
private lateinit var bind: ActivityUpdatepositionBinding
private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
//private lateinit var lat: String // :Double
//private lateinit var long: String // ||.toDouble
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
bind = ActivityUpdatepositionBinding.inflate(layoutInflater)
setContentView(bind.root)
//supportActionBar!!.hide()
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
try {
getActualLocation()
//getActualLocation()
//getActualLocation()
}catch (e: java.lang.Exception){
e.printStackTrace()
}
}
private fun getActualLocation() {
val task = fusedLocationProviderClient.lastLocation
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){
ActivityCompat.requestPermissions(this, arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION), 101)
return
}
task.addOnSuccessListener {
if (it != null){
bind.tvLatitude.text = "${it.latitude}" // it.longitude is a Double
bind.tvLongitude.text = "${it.longitude}" // tvLongitude is a TextView
}
}
}// one curly brace could be missing (or not)
run it then close your app then run again and voila!

Categories

Resources