How To Find My Current Location (latitude + Longitude) On Click Of A Button In Android?
Solution 1:
Yogsma's answer addresses how to receive automatic updates. The link he references provides all you need, but here is the summarized version of how to do a manual update:
Assuming you've read the tutorials on how to make a button, then you simply need to add a listener for your button, and then have the listener call a function to query your location manager. The code below does it all inline to show you how, but I'd instantiate LocationManager somewhere else (eg your activity) and I'd create a separate method for the on click listener to call to perform the update.
// getLocationButton is the name of your button. Not the best name, I know.
getLocationButton.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
// instantiate the location manager, note you will need to request permissions in your manifestLocationManagerlocationManager= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// get the last know location from your location manager.
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// now get the lat/lon from the location and do something with it.
nowDoSomethingWith(location.getLatitude(), location.getLongitude());
}
});
Of course you will also need to register your activity with the location manager service in your manifest xml file:
<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION" />
Solution 2:
LocationManager mLocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mLocListener = newMyLocationListener();
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocListener);
publicclassMyLocationListenerimplementsLocationListener{
publicvoidonLocationChanged(Location loc) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
loc.getLongitude(), loc.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
publicvoidonProviderDisabled(String arg0) {
}
publicvoidonProviderEnabled(String provider) {
}
publicvoidonStatusChanged(String provider, int status, Bundle extras) {
}
}
Read this for detail http://www.javacodegeeks.com/2010/09/android-location-based-services.html
Solution 3:
There is no such mechanism to get the current location immediately on demand. Since you need to query the Netowork or the GPS provider which may take time to actually get the location.
One way is to use the getLastKnownLocation which returns immediately. However this location may be stale. Another way is to register for a PASSIVE_PROVIDER by which you get a location fix with the hope that some other application has requested for location.
Post a Comment for "How To Find My Current Location (latitude + Longitude) On Click Of A Button In Android?"