🌐
Google Support
support.google.com › maps › answer › 18539
Search by latitude & longitude in Google Maps - Android - Google Maps Help
To search for a place on Google Maps, enter the latitude and longitude GPS coordinates. You can also find the coordinates of the places you previously found. Besides longitude and latitude, you can u
🌐
GPS Coordinates
gps-coordinates.net
GPS coordinates, latitude and longitude with interactive Maps
Find the GPS Coordinates of any address or vice versa. Get the latitude and longitude of any GPS location on Earth with our interactive Maps.
Discussions

java - How to get Latitude and Longitude of the mobile device in android? - Stack Overflow
If you're already using ... developer.android.com/guide/topics/location/strategies.html 2017-10-14T23:04:17.39Z+00:00 ... I used this code and the nedded permissions but longitude and latitude are null..where is the error here? 2018-11-25T23:28:29.633Z+00:00 ... Here is the class LocationFinder to find the GPS location. This class will call MyLocation, which will ... More on stackoverflow.com
🌐 stackoverflow.com
java - Finding the latitude and longitude values for the device's current location in Android with Google Maps API - Stack Overflow
So there are many similar questions asked based on this, and I have also got a working solution. However, this seems to only work on my physical Android device. If I were to use it with the emulato... More on stackoverflow.com
🌐 stackoverflow.com
google maps - How to get latitude and longitude of current location in Android? - Stack Overflow
I have a Fragment in which I want to show current location of user(device). I use Google Map Android API v2. How get current latitude and longitude of device? Here below you can see code that I us... More on stackoverflow.com
🌐 stackoverflow.com
How to get the current location latitude and longitude in android - Stack Overflow
In my application, I get the current location's latitude and longitude when application is open, but not when the application is closed. I am using Service class to get the current location latitu... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

How to find my latitude and longitude on Google Maps Android?
To find your latitude and longitude on Google Maps for Android, follow these steps: 1. Open the Google Maps app on your Android device. 2. Ensure that your location services (GPS) are enabled on your phone. You can do this by going to your device's Settings > Location > GPS, and making sure it is turned on. 3. Once inside the Google Maps app, tap on the blue dot that represents your current location on the map. This will typically be centered on the screen and indicate your approximate location. 4. By tapping on the blue dot, a small box will appear at the bottom, showing your exact lat
🌐
tunesbro.com
tunesbro.com › home › how to get current location longitude and latitude on android?
How to Get Current Location Longitude And Latitude on Android?
Does Google Maps app show latitude and longitude?
Yes, the Google Maps app does show latitude and longitude coordinates. Here's how you can access them: 1. Open the Google Maps app on your device. 2. Search for the desired location by either typing in the address or dropping a pin on the map. 3. Once the location is displayed, tap and hold on the specific area you're interested in. This will drop a pin on that spot. 4. At the bottom of the screen, you'll see information about the location, including its address and coordinates (latitude and longitude). The latitude and longitude will be displayed in a format like "36.123456, -118.654321". 5.
🌐
tunesbro.com
tunesbro.com › home › how to get current location longitude and latitude on android?
How to Get Current Location Longitude And Latitude on Android?
How do I find my current GPS location on Google Maps?
To find your current GPS location on Google Maps, follow these steps: 1. Open the Google Maps application on your smartphone or access it through your web browser on a computer. 2. Ensure that your device's location services are enabled. On a smartphone, this can usually be found in the device's settings under "Location" or "Privacy." On a computer, you may need to grant permission for your web browser to access your location. 3. Once you have confirmed that your location services are enabled, Google Maps will usually display your current location automatically with a blue dot on the map.
🌐
tunesbro.com
tunesbro.com › home › how to get current location longitude and latitude on android?
How to Get Current Location Longitude And Latitude on Android?
🌐
Google Play
play.google.com › store › apps › details
Latitude Longitude - Apps on Google Play
This Latitude app allows you to see your current gps location based on latitude and longitude on the map and share location whenever you want. You can share your GPS location (latitude and longitude) on the map with your friends and your family.
Rating: 4.6 ​ - ​ 18.7K votes
🌐
GPS Coordinates
gps-coordinates.org
GPS Coordinates - Latitude and Longitude Finder
GPS Coordinates finder is a tool used to find the latitude and longitude of your current location including your address, zip code, state, city and latlong. The latitude and longitude finder to convert gps location to address or search for your address and latitude and longitude on the map ...
🌐
Wikihow
wikihow.com › computers and electronics › internet › website application instructions › google applications › google maps › how to get latitude and longitude from google maps
How to Get Latitude and Longitude from Google Maps
February 19, 2026 - We'll also show you how to search by latitude and longitude, and how to use an alternative to those coordinates called plus codes. On an Android, tap and hold a location on the map to show latitude and longitude in the Search bar.
🌐
TunesBro
tunesbro.com › home › how to get current location longitude and latitude on android?
How to Get Current Location Longitude And Latitude on Android?
August 8, 2023 - The format will typically be displayed as "Latitude: XX.XXXXXX, Longitude: XX.XXXXXX". 5. You can also long-press on any location on the map to manually get the latitude and longitude coordinates for that specific point.
🌐
Quora
quora.com › How-do-you-find-your-latitude-and-longitude-on-your-phone
How to find your latitude and longitude on your phone - Quora
4) Using Google’s “What’s here?” (Web browser) In a mobile browser, go to maps.google.com. Tap and hold your location on the map to drop a pin; coordinates appear at the top or bottom.
Find elsewhere
Top answer
1 of 9
355

Use the LocationManager.

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();

The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.

private final LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    }
}

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);

You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.

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

You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.

2 of 9
42

Here is the class LocationFinder to find the GPS location. This class will call MyLocation, which will do the business.

LocationFinder

public class LocationFinder extends Activity {

    int increment = 4;
    MyLocation myLocation = new MyLocation();

    // private ProgressDialog dialog;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.intermediat);
        myLocation.getLocation(getApplicationContext(), locationResult);

        boolean r = myLocation.getLocation(getApplicationContext(),
            locationResult);

        startActivity(new Intent(LocationFinder.this,
        // Nearbyhotelfinder.class));
            GPSMyListView.class));
        finish();
    }

    public LocationResult locationResult = new LocationResult() {

        @Override
        public void gotLocation(Location location) {
            // TODO Auto-generated method stub
            double Longitude = location.getLongitude();
            double Latitude = location.getLatitude();

            Toast.makeText(getApplicationContext(), "Got Location",
                Toast.LENGTH_LONG).show();

            try {
                SharedPreferences locationpref = getApplication()
                    .getSharedPreferences("location", MODE_WORLD_READABLE);
                SharedPreferences.Editor prefsEditor = locationpref.edit();
                prefsEditor.putString("Longitude", Longitude + "");
                prefsEditor.putString("Latitude", Latitude + "");
                prefsEditor.commit();
                System.out.println("SHARE PREFERENCE ME PUT KAR DIYA.");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    // handler for the background updating

}

MyLocation

public class MyLocation {

    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled=false;
    boolean network_enabled=false;

    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){}

        //Toast.makeText(context, gps_enabled+" "+network_enabled,     Toast.LENGTH_LONG).show();

        //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(), 10000);
    //    Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show();
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            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) {
            timer1.cancel();
            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) {}
    };

    class GetLastLocation extends TimerTask {
        @Override

        public void run() {

            //Context context = getClass().getgetApplicationContext();
             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);
        }
    }

    public static abstract class LocationResult{
        public abstract void gotLocation(Location location);
    }
}
🌐
Google Play
play.google.com › store › apps › details
Latitude Longitude Coordinates - Apps on Google Play
March 26, 2026 - With just a few taps, you'll unlock detailed latitude and longitude data, making it the ideal app for travelers, explorers, and anyone who depends on coordinates daily. Key Features: • Instant Latitude and Longitude Lookup: Get accurate location readings for any place in the world.
Rating: 4.3 ​ - ​ 985 votes
🌐
Softonic
latitude-longitude.en.softonic.com › home › android › travel & navigation › maps & gps › latitude longitude
Latitude Longitude for Android - Download
December 13, 2025 - Latitude Longitude for Android, free and safe download. Latitude Longitude latest version: Free Smartphone Application to Access Map-Related Commands.
Rating: 7.5/10 ​ - ​ 11 votes
🌐
Latitude and Longitude Finder
latlong.net › home › geo tools
My Location Finder - My Latitude and Longitude
Once your location is detected, it shows your latitude and longitude in easy-to-read fields and allows you to copy them instantly for use in maps, travel planning, geotagging, or any project that requires accurate positioning. Powered by Leaflet and OpenStreetMap, this tool ensures a fast, interactive, and mobile-friendly experience.
Top answer
1 of 1
1

This code works just fine in one of my projects:

Copypublic class LocationManager {
        private static LocationManager requestManager;
        private FusedLocationProviderClient mLocationProviderClient;
        private Location mLocation;
        private Location mMyCurrentLocation;
        private locationSuccessListener mListener;

    public Location getLocation() {
        return mLocation;
    }

    public void setLocation(Location location) {
        mLocation = location;
    }

    private LocationManager(FusedLocationProviderClient fusedLocationProviderClient) {
        this.mLocationProviderClient = fusedLocationProviderClient;
    }

    public static LocationManager createInstance(FusedLocationProviderClient fusedLocationProviderClient) {
        if (requestManager != null) {
            return requestManager;
        } else {
            return requestManager = new LocationManager(fusedLocationProviderClient);
        }
    }

    public static LocationManager getInstance() {
        return requestManager;
    }

    public void setLocation(Activity activity) {
        mListener = (locationSuccessListener) activity;
        LocationCallback callback = new LocationCallback();
        LocationRequest locationRequest = new LocationRequest();
        Task<Void> r = mLocationProviderClient.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper());
        r.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                mLocationProviderClient.getLastLocation().addOnSuccessListener(activity, new OnSuccessListener<Location>() {
                    @Override
                    public void onSuccess(Location location) {
                        mMyCurrentLocation = location;
                        mLocation = location;
                        if (location != null) {
                            mListener.onLocationReceived();
                            mLocationProviderClient.removeLocationUpdates(callback);
                        }
                    }
                });
            }
        });


    }

    public Location getMyCurrentLocation() {
        return mMyCurrentLocation;
    }


    public interface locationSuccessListener {
        void onLocationReceived();
    }

You need to do something like that:

Copypublic class PlacesActivity extends SingleFragmentActivity implements NavigationView.OnNavigationItemSelectedListener, LocationManager.locationSuccessListener

and then in your activity you will get this:

Copy@Override
    public void onLocationReceived() {
         Location l = LocationManager.getInstance().getMyCurrentLocation();
             if (l==null){
                 Toast.makeText(this, "unable to get location", Toast.LENGTH_SHORT).show();
                 
             }
    }

to get permission you suppose to do something like this:

Copyif (ContextCompat.checkSelfPermission(Objects.requireNonNull(getActivity()), Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    0);
            
🌐
Alpinesavvy
alpinesavvy.com › blog › know-how-to-find-your-coordinates-from-your-phone
Know how to find your coordinates from your phone — Alpinesavvy
December 30, 2024 - The better choice is to use latitude longitude decimal degree format, which is universally understood by everybody. Android folks, try searching in the Google app store for “GPS location”. There are all kinds of free apps.
🌐
GIS Geography
gisgeography.com › home › software › gps coordinate apps: find your gps location
GPS Coordinate Apps: Find Your GPS Location - GIS Geography
October 29, 2023 - For Android users, Google Maps is the simplest way to either enter latitude and longitude coordinates or to find out your current coordinates.
🌐
Whatsmygps
whatsmygps.com
Latitude and Longitude - Find your Latitude and Longitude Map Location - GPS Coordinates
Welcome to WhatsMyGPS.com, an easy way to find the latitude and longitude location of any place on Earth! It's a great way to share your address, favourite locations, travel destinations, or Geocaching coordinates. You can also use WhatsMyGPS.com to get GPS location coordinates for your handheld ...
Top answer
1 of 8
124

Before couple of months, I created GPSTracker library to help me to get GPS locations. In case you need to view GPSTracker > getLocation

Demo

AndroidManifest.xml

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

Activity

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.geo_locations);

        // check if GPS enabled
        GPSTracker gpsTracker = new GPSTracker(this);

        if (gpsTracker.getIsGPSTrackingEnabled())
        {
            String stringLatitude = String.valueOf(gpsTracker.latitude);
            textview = (TextView)findViewById(R.id.fieldLatitude);
            textview.setText(stringLatitude);

            String stringLongitude = String.valueOf(gpsTracker.longitude);
            textview = (TextView)findViewById(R.id.fieldLongitude);
            textview.setText(stringLongitude);

            String country = gpsTracker.getCountryName(this);
            textview = (TextView)findViewById(R.id.fieldCountry);
            textview.setText(country);

            String city = gpsTracker.getLocality(this);
            textview = (TextView)findViewById(R.id.fieldCity);
            textview.setText(city);

            String postalCode = gpsTracker.getPostalCode(this);
            textview = (TextView)findViewById(R.id.fieldPostalCode);
            textview.setText(postalCode);

            String addressLine = gpsTracker.getAddressLine(this);
            textview = (TextView)findViewById(R.id.fieldAddressLine);
            textview.setText(addressLine);
        }
        else
        {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gpsTracker.showSettingsAlert();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
        return true;
    }
}

GPS Tracker

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

/**
 * Create this Class from tutorial : 
 * http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
 * 
 * For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
 * 
 */

public class GPSTracker extends Service implements LocationListener {

    // Get Class Name
    private static String TAG = GPSTracker.class.getName();

    private final Context mContext;

    // flag for GPS Status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS Tracking is enabled 
    boolean isGPSTrackingEnabled = false;

    Location location;
    double latitude;
    double longitude;

    // How many Geocoder should return our GPSTracker
    int geocoderMaxResults = 1;

    // The minimum distance to change updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
    private String provider_info;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    /**
     * Try to get my current location by GPS or Network Provider
     */
    public void getLocation() {

        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            //getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            //getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            // Try to get location if you GPS Service is enabled
            if (isGPSEnabled) {
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use GPS Service");

                /*
                 * This provider determines location using
                 * satellites. Depending on conditions, this provider may take a while to return
                 * a location fix.
                 */

                provider_info = LocationManager.GPS_PROVIDER;

            } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use Network State to get GPS coordinates");

                /*
                 * This provider determines location based on
                 * availability of cell tower and WiFi access points. Results are retrieved
                 * by means of a network lookup.
                 */
                provider_info = LocationManager.NETWORK_PROVIDER;

            } 

            // Application can use GPS or Network Provider
            if (!provider_info.isEmpty()) {
                locationManager.requestLocationUpdates(
                    provider_info,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, 
                    this
                );

                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(provider_info);
                    updateGPSCoordinates();
                }
            }
        }
        catch (Exception e)
        {
            //e.printStackTrace();
            Log.e(TAG, "Impossible to connect to LocationManager", e);
        }
    }

    /**
     * Update GPSTracker latitude and longitude
     */
    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }

    /**
     * GPSTracker latitude getter and setter
     * @return latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        return latitude;
    }

    /**
     * GPSTracker longitude getter and setter
     * @return
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        return longitude;
    }

    /**
     * GPSTracker isGPSTrackingEnabled getter.
     * Check GPS/wifi is enabled
     */
    public boolean getIsGPSTrackingEnabled() {

        return this.isGPSTrackingEnabled;
    }

    /**
     * Stop using GPS listener
     * Calling this method will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to show settings alert dialog
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        //Setting Dialog Title
        alertDialog.setTitle(R.string.GPSAlertDialogTitle);

        //Setting Dialog Message
        alertDialog.setMessage(R.string.GPSAlertDialogMessage);

        //On Pressing Setting button
        alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        //On pressing cancel button
        alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                dialog.cancel();
            }
        });

        alertDialog.show();
    }

    /**
     * Get list of address by latitude and longitude
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses 
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Note

If the method / answer doesn't work. You need to use the official Google Provider: FusedLocationProviderApi.

Article: Getting the Last Known Location

2 of 8
60

IMPORTANT:

Please notice this solution is from 2015 might be too old and deprecated.


None of the above worked for me so I made a tutorial and wrote it for myself since I lost many hours trying to implement this. Hope this helps someone:

How to use Google Play Services LOCATION API to get current latitude & longitude

1) Add to your AndroidManifest.xml file the ACCESS_COARSE_LOCATION & ACCESS_FINE_LOCATION:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" >

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

        <application...

2) Go to app/build.gradlefile and add the following dependency (make sure to use the latest available version):

    dependencies {
        //IMPORTANT: make sure to use the newest version. 11.0.1 is old AF
        compile 'com.google.android.gms:play-services-location:11.0.1
    }

3) In your activity implement the following:

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.GoogleMap;

    public class HomeActivity extends AppCompatActivity implements
            ConnectionCallbacks,
            OnConnectionFailedListener,
            LocationListener {

        //Define a request code to send to Google Play services
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private double currentLatitude;
        private double currentLongitude;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_home);

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    // The next two lines tell the new client that “this” current class will handle connection stuff
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    //fourth line adds the LocationServices API endpoint from GooglePlayServices
                    .addApi(LocationServices.API)
                    .build();

            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        }

        @Override
        protected void onResume() {
            super.onResume();
            //Now lets connect to the API
            mGoogleApiClient.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
            Log.v(this.getClass().getSimpleName(), "onPause()");

            //Disconnect from API onPause()
            if (mGoogleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                mGoogleApiClient.disconnect();
            }


        }

        /**
         * If connected get lat and long
         * 
         */
        @Override
        public void onConnected(Bundle bundle) {
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            } else {
                //If everything went fine lets get latitude and longitude
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();

                Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
            }
        }


        @Override
        public void onConnectionSuspended(int i) {}

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
                Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
            }
        }

        /**
         * If locationChanges change lat and long
         * 
         * 
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }

    }

If you need more info just go to:

The Beginner’s Guide to Location in Android

Note: This doesn't seem to work in the emulator but works just fine on a device

🌐
Medium
sachankapil.medium.com › latest-method-how-to-get-current-location-latitude-and-longitude-in-android-give-support-for-c5132474c864
Latest Method: How to get Current Location (Latitude and Longitude) in Android & Give support for…
January 27, 2023 - val lastKnownLocationByGps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)lastKnownLocationByGps?.let { locationByGps = lastKnownLocationByGps }//------------------------------------------------------//val lastKnownLocationByNetwork = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)lastKnownLocationByNetwork?.let { locationByNetwork = lastKnownLocationByNetwork }//------------------------------------------------------//if (locationByGps != null && locationByNetwork != null) { if (locationByGps.accuracy > locationByNetwork!!.accuracy) { currentLocation