Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current location in Android [duplicate]

People also ask

How we get the current location in Android?

There are two ways to get the current location of any Android device: Android's Location Manager API. Fused Location Provider: Google Play Services Location APIs.

How can I capture current location?

Quick tip: In the iPhone and Android apps, tapping the Current Location button twice will turn on compass mode. The app will center on your location, but the map will rotate to match the direction you're currently facing in real life.

How do I compare two locations on Android?

import android. location. Location float[] distance = new float[1]; Location. distanceBetween(lat, lon, currentLat, currentLon, distance); // distance[0] is now the distance between these lat/lons in meters if (distance[0] < 2.0) { // your code... }


First you need to define a LocationListener to handle location changes.

private final LocationListener mLocationListener = new LocationListener() {
    @Override
    public void onLocationChanged(final Location location) {
        //your code here
    }
};

Then get the LocationManager and ask for location updates

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
            LOCATION_REFRESH_DISTANCE, mLocationListener);
}

And finally make sure that you have added the permission on the Manifest,

For using only network based location use this one

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

For GPS based location, this one

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

You need to write code in the OnLocationChanged method, because this method is called when the location has changed. I.e. you need to save the new location to return it if getLocation is called.

If you don't use the onLocationChanged it always will be the old location.


I'm using this tutorial and it works nicely for my application.

In my activity I put this code:

GPSTracker tracker = new GPSTracker(this);
    if (!tracker.canGetLocation()) {
        tracker.showSettingsAlert();
    } else {
        latitude = tracker.getLatitude();
        longitude = tracker.getLongitude();
    }

also check if your emulator runs with Google API