I recently added get location function. When I try to show longitude and latitude, it returns zero.
This my LocationListener class:
inner class Myloc
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
// 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) {}
}