You are getting it from LocationManager::getLastKnownLocation()
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Answer from azizbekian on Stack OverflowYou are getting it from LocationManager::getLastKnownLocation()
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
This is my code its working for my App. You can try it to fetch the Location.
ro_gps_icon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(RODetailsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(RODetailsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
} locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, (LocationListener) RODetailsActivity.this);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location == null) {
Toast.makeText(getApplicationContext(), "GPS signal not found", Toast.LENGTH_SHORT).show();
}
if (location != null) {
Log.e("locatin", "location--" + location);
Log.e("latitude at beginning",
"@@@@@@@@@@@@@@@" + location.getLatitude());
onLocationChanged(location);
}
}
});
and method for getting the data.
public void onLocationChanged(Location location) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.e("latitude", "latitude--" + latitude);
try {
Log.e("latitude", "inside latitude--" + latitude);
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
ro_gps_location.setText(state + " , " + city + " , " + country);
ro_address.setText(address + " , " + knownName + " , " + postalCode);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Videos
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(new OnClickListener() {
@Override
public void onClick(View v) {
// instantiate the location manager, note you will need to request permissions in your manifest
LocationManager locationManager = (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-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
LocationManager mLocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mLocListener = new MyLocationListener();
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocListener);
public class MyLocationListener implements LocationListener{
public void onLocationChanged(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();
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Read this for detail http://www.javacodegeeks.com/2010/09/android-location-based-services.html
You can add listener on button click.
Button btnMyLocation = (Button) findViewById(R.id.btnMyLocation);
CameraUpdate cameraUpdate = null;
btnMyLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Location loc = map.getMyLocation();
if (loc != null) {
LatLng latLng = new LatLng(loc.getLatitude(), loc
.getLongitude());
cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 17);
map.animateCamera(cameraUpdate);
}
}
});
for GPS :
You require following permission in Manifest file
android.permission.ACCESS_FINE_LOCATION
and here is code :
final LocationManager manager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) )
Toast.makeText(context, "GPS is disable!", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "GPS is Enable!", Toast.LENGTH_LONG).show();
Just start a location Update listener on the click of that button. and when new location arrives move the camera in mapObject (got in OnMapReady() method) to that location with animations.
this is what i am doing in my case :
MyLocation class :
import android.app.ProgressDialog;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
public class MyLocation {
// Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
AsyncTask<Context, Void, Void> mtask;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
// timer1=new Timer();
// timer1.schedule(new GetLastLocation(), 20000);
mtask= new GetLastLocation().execute();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
// timer1.cancel();
mtask.cancel(true);
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
mtask.cancel(true);
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private Context mContext;
public MyLocation(Context c) { this.mContext = c; }
class GetLastLocation extends AsyncTask<Context, Void, Void>
{
ProgressDialog dialog = new ProgressDialog(mContext);
protected void onPreExecute()
{
dialog.setMessage("Searching....");
dialog.show();
}
protected Void doInBackground(Context... params)
{
Handler mHandler = new Handler(Looper.getMainLooper());
// ...
mHandler.post(new Runnable() {
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
});
// ...
return null;
}
protected void onPostExecute(final Void unused)
{
dialog.dismiss();
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
and the method for button click :
MyLocation myLocation = new MyLocation();
private void locationClick() {
myLocation.getLocation(this, locationResult));
}
public LocationResult locationResult = new LocationResult(){
@Override
public void gotLocation(final Location location){
//Got the location!
});
}
};
I have found this from an older post in stackoverflow when i was looking solution for the similar issue......
You have use this method to check all enable providers
void requestLocationUpdates()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
List<String> enabledProviders = this.locationManager.getProviders(true);
for (String provider:enabledProviders){
Log.i(">>>>>>>", "Requesting location updates from provider " + provider);
this.locationManager.requestLocationUpdates(provider, 10000l, 10, this);
}
}
Since this question was posted, Google has updated the API. They have added an onMyLocationButtonClick() listener.
To add the listener:
//add location button click listener
map.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener(){
@Override
public boolean onMyLocationButtonClick()
{
//TODO: Any custom actions
return false;
}
});
Returning false will essentially call the super method. Returning true will not.
The latest release of Google Maps android api V2 in August contains a listener method for clicks of my location button : onMyLocationButtonClick () This can be used to know when the user has clicked the button and returns true if the listener has consumed the event
You can use this to get address corresponding to the latitude and longitude
Geocoder geocoder;
List<Address> address;
geocoder = new Geocoder(this, Locale.getDefault());
address = geocoder.getFromLocation(latitude, longitude, 1);
then use this
String city = address.get(0).getLocality();
String state = address.get(0).getAdminArea();
use this method
public void setUpCurrentLocation(double latitude, double longitude) {
if (latitude == 0 || longitude == 0)
return;
LatLng latLng = new LatLng(latitude, longitude);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, AppConstants.MAP_MAX_ZOOM);
mGoogleMap.animateCamera(cameraUpdate);
}
map.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {
@Override
public boolean onMyLocationButtonClick() {
Toast.makeText(
getActivity(),
"Example de Message for Android",
Toast.LENGTH_SHORT).show();
return true;
}
});
To get the current location after clicking MyLocationButton, then use
`googleMap.getMyLocation(); //Deprecated, So use `googleMap.setMyLocationEnabled(true); //Which allows to deal with current location`
inside setOnMyLocationButtonClickListener.
Reference link: https://www.androidtutorialpoint.com/intermediate/android-map-app-showing-current-location-android/
Hope it helps ! And thanks to Cabezas.