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 Overflow
🌐
Google
developers.google.com › google maps platform › android › maps sdk for android › show my location
Show My Location | Maps SDK for Android | Google for Developers
PermissionUtils.requestLocationPermissions(this, LOCATION_PERMISSION_REQUEST_CODE, true); } @Override public boolean onMyLocationButtonClick() { Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show(); // Return false so that we don't consume the event and the default behavior still occurs // (the camera animates to the user's current position). return false; } @Override public void onMyLocationClick(@NonNull Location location) { Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show(); } @Override public void onRequestPermissionsResult(int requestC
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-implement-current-location-button-feature-in-google-maps-in-android
How to Implement Current Location Button Feature in Google Maps in Android? - GeeksforGeeks
May 23, 2021 - Through this article, while we will be implementing Google Maps, we shall also be implementing a button, which will fetch our current location and navigate it on the map. Note that we are going to implement this project using the Kotlin language. Screenshot of the actual Google Map App on Android device
Discussions

android - why i can't get my current location through a button - Stack Overflow
what i really need to do is when i press the location button is to get my current location and display it like an address in edit text without map .. but it keep giving me NULL POINTER EXCEPTION .... More on stackoverflow.com
🌐 stackoverflow.com
Android get Location in Button click - Stack Overflow
I try to get the location in button click. I wrote LocationListener method and everything working perfect.This is my source private class MyLocationListener implements LocationListener { @Ove... More on stackoverflow.com
🌐 stackoverflow.com
Get Current Position in Google Map when Click on Android Button - Stack Overflow
I implement map in my device successfully. but now I want to add functionality When I click on Button then I want to get Current Location in map.How can I do that? More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
Location button not enabled in android google maps - Stack Overflow
What i have: I have a running google maps What is happening: I cannot see the location button on the map What i want Code: i have called this function in oncreate, i have instance of google m... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Google
developers.google.com › google maps platform › android › maps sdk for android › select current place and show details on a map
Select Current Place and Show Details on a Map | Maps SDK for Android | Google for Developers
Find the CurrentPlaceDetailsOnMap project at this location: PATH-TO-SAVED-REPO/android-samples/tutorials/java/CurrentPlaceDetailsOnMap (Java) or PATH-TO-SAVED-REPO/android-samples/tutorials/kotlin/CurrentPlaceDetailsOnMap (Kotlin) Select the project directory, then click Open. Android Studio now builds your project, using the Gradle build tool. To complete this tutorial, you need a Google Cloud project with the necessary APIs enabled and an API key that's authorized to use the Maps SDK for Android.
🌐
Google
developers.google.com › google play services › googlemap.onmylocationbuttonclicklistener
GoogleMap.OnMyLocationButtonClickListener | Google Play services | Google for Developers
April 27, 2021 - The GoogleMap.OnMyLocationButtonClickListener interface is used for callbacks when the My Location button is clicked · The onMyLocationButtonClick method is called on the Android UI thread when the my location button is clicked
🌐
Stack Overflow
stackoverflow.com › questions › 23719427 › why-i-cant-get-my-current-location-through-a-button
android - why i can't get my current location through a button - Stack Overflow
public class PersonalInfo extends Activity{ private GoogleMap googleMap; Geocoder geocoder; EditText addressnew; GPSTracker gps; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.personal_info); EditText name=(EditText)findViewById(R.id.edittext1); EditText mobile=(EditText)findViewById(R.id.edittext2); addressnew=(EditText)findViewById(R.id.editText3); Button location=(Button)findViewById(R.id.button1); Button send=(Button)findViewById(R.id.button2); location.setOnClick
Top answer
1 of 2
1

You are getting it from LocationManager::getLastKnownLocation()

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
2 of 2
1

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();
    }
}
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 10565365 › how-to-get-a-current-location-on-map-after-clicking-button-in-android-project
How to get a current location on map after clicking button in android project? - Stack Overflow
You can read more about the MapView ... you want the map to be moved when the search button is clicked, then put it in your search button's OnClickListener....
🌐
Stack Overflow
stackoverflow.com › questions › 19077204 › androidhow-to-set-the-current-location-to-a-location-object-on-click-of-a-butt
onclick - [Android]How to set the current location to a location object on click of a button? - Stack Overflow
The left hand side should be a TextView or whatever you want to tell the current location. ... The code will enter a loop, continuously setting the latitude variable. Please try and follow this guide: http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
Top answer
1 of 5
34

See below xml file to custom button:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/maps"
        android:name="pl.mg6.android.maps.extensions.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dp" >

        <ImageView
            android:id="@+id/imgMyLocation"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:scaleType="fitXY"
            android:src="@drawable/track_my_location" />
    </LinearLayout>

</RelativeLayout>

Then in java class, declare your location button:

private ImageView imgMyLocation;
        imgMyLocation = (ImageView) findViewById(R.id.imgMyLocation);

Click Event:

imgMyLocation.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getMyLocation();

}

Get Location Method, in that just pass your current latitude and longitude.

private void getMyLocation() {
        LatLng latLng = new LatLng(Double.parseDouble(getLatitude()), Double.parseDouble(getLongitude()));
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 18);
        googleMap.animateCamera(cameraUpdate);
    }
    });
2 of 5
19

With a simple trick, you can replace the my location button with a custom one.

  1. Customize the Layout of your new button.
  2. Set my location enabled in maps api.
  3. Hide default button of my location.
  4. call click method of my location on your custom button click.

1. Customize the layout of your new button

add a new button to your desired location in layout file of map activity.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:map="http://schemas.android.com/apk/res-auto"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_height="match_parent"
     android:layout_width="match_parent">

    <fragment
         android:id="@+id/map"
         android:name="com.google.android.gms.maps.SupportMapFragment"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         tools:context=".activities.MapsActivity" />

   <ImageView
        android:id="@+id/ic_location"
        android:layout_width="18dp"
        android:layout_height="18dp"
        android:src="@drawable/ic_location"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="18dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"/>
</RelativeLayout>

2. Set my location enabled in maps api

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Enable My Location
    mMap.setMyLocationEnabled(true);
    /* and DON'T disable the default location button*/
 }

3. Hide default button of my location.

    //Create field for map button.
    private View locationButton;

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);

        // get your maps fragment
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
        // Extract My Location View from maps fragment 
        locationButton = mapFragment.getView().findViewById(0x2);
        // Change the visibility of my location button
        if(locationButton != null)
            locationButton.setVisibility(View.GONE);
    }

4. call click method of my location on your custom button click.

findViewById(R.id.ic_location).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(mMap != null)
            {
                if(locationButton != null)
                    locationButton.callOnClick();

            }
         }
    });
🌐
Stack Overflow
stackoverflow.com › questions › 35233104 › how-to-set-current-location-in-start-of-the-app
android - how to set current location in start of the app? - Stack Overflow
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, Manifest.permission.ACCESS_FINE_LOCATION, true); setUpMap(); } else if (mMap != null) { // Access to the location has been granted to the app. mMap.setMyLocationEnabled(true); } } @Override public boolean onMyLocationButtonClick() { Toast.makeText(this, "MyLocation button clicked"+mMap.getMyLocation().getLatitude(), Toast.LENGTH_SHORT).show(); // Return false so that we don't consume the event and the default behavior still occurs // (the camera animates to the user's current position).
Top answer
1 of 16
38

you can use this

View locationButton = ((View) mMapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
// position on right bottom
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
rlp.setMargins(0, 180, 180, 0);
2 of 16
31

I solved this problem in my map fragment by re positioning my location button to the right bottom corner of view using code below, here is my MapsActivity.java :-

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    View mapView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapView = mapFragment.getView();
        mapFragment.getMapAsync(this);
            }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMyLocationEnabled(true);

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));

        if (mapView != null &&
                mapView.findViewById(Integer.parseInt("1")) != null) {
            // Get the button view
            View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
            // and next place it, on bottom right (as Google Maps app)
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
                    locationButton.getLayoutParams();
            // position on right bottom
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
            layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
            layoutParams.setMargins(0, 0, 30, 30);
        }

    }
}

And here is layout of fragment :-

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.infogird.www.location_button_reposition.MapFragment">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</FrameLayout>

I hope, this will solve your problem. Thanks.

Top answer
1 of 8
131

Use below code to check. If it is disabled, dialog box will be generated

public void statusCheck() {
    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        buildAlertMessageNoGps();

    }
}

private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}
2 of 8
19

Here is a simple way of programmatically enabling location like Maps app:

protected void enableLocationSettings() {
       LocationRequest locationRequest = LocationRequest.create()
             .setInterval(LOCATION_UPDATE_INTERVAL)
             .setFastestInterval(LOCATION_UPDATE_FASTEST_INTERVAL)
             .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);

        LocationServices
                .getSettingsClient(this)
                .checkLocationSettings(builder.build())
                .addOnSuccessListener(this, (LocationSettingsResponse response) -> {
                    // startUpdatingLocation(...);
                })
                .addOnFailureListener(this, ex -> {
                    if (ex instanceof ResolvableApiException) {
                        // Location settings are NOT satisfied,  but this can be fixed  by showing the user a dialog.
                        try {
                            // Show the dialog by calling startResolutionForResult(),  and check the result in onActivityResult().
                            ResolvableApiException resolvable = (ResolvableApiException) ex;
                            resolvable.startResolutionForResult(TrackingListActivity.this, REQUEST_CODE_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException sendEx) {
                            // Ignore the error.
                        }
                    }
                });
 }

And onActivityResult:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (REQUEST_CODE_CHECK_SETTINGS == requestCode) {
        if(Activity.RESULT_OK == resultCode){
            //user clicked OK, you can startUpdatingLocation(...);

        }else{
            //user clicked cancel: informUserImportanceOfLocationAndPresentRequestAgain();
        }
    }
}

You can see the documentation here: https://developer.android.com/training/location/change-location-settings

🌐
GitHub
github.com › mapbox › mapbox-gl-native › issues › 3365
how can i show my location button like google map · Issue #3365 · mapbox/mapbox-gl-native
December 21, 2015 - in google map if i open there is a function to set my location button enable and disable "gmaps.getUiSettings().setMyLocationButtonEnabled(false);" same way is there any function in mapbox sdk to enable or disable? or we need to write our own logic
Author   mapbox
🌐
Android Developers
developer.android.com › core areas › sensors and location › change location settings
Change location settings | Sensors and location | Android Developers
In order to use the location services ... location provider, connect your app using the Settings Client, then check the current location settings and prompt the user to enable the required settings if needed....
🌐
GitHub
gist.github.com › bdiegel › 3107218187008ca9a05e
Android Maps v2 MyLocation Button Position · GitHub
It's easy to enable Zoom and MyLocation buttons but annoying to change where they overlay the Map. ... private void setUpMap() { // Find myLocationButton view SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); View myLocationButton = mapFragment.getView().findViewById(0x2); if (myLocationButton != null && myLocationButton.getLayoutParams() instanceof RelativeLayout.LayoutParams) { // location button is inside of RelativeLayout RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myLocationButton.getLayoutParams(); // Alig
🌐
Reddit
reddit.com › r/reactnative › current location button with different positioning in android & ios. any way to alter it !?
r/reactnative on Reddit: Current location button with different positioning in android & iOS. Any way to alter it !?
December 25, 2022 -

So I'm working with locations and maps in React Native. Currently using react-native-maps.

I need to show the current location button on the maps so that when the user taps it the map takes the user to the user's current location.

For now I'm able to enable the current location and the current location for the button. But the positioning in android and in iOS is a little different. In android I get the button on the top right and on the iOS I get the button on the bottom right.

Is there a way to actually alter the positioning of the button without having to use a custom button and using the same default button of the map ?

🌐
TheLinuxCode
thelinuxcode.com › home › how to get current location in android (practical, modern, and reliable)
How to Get Current Location in Android (Practical, Modern, and Reliable) – TheLinuxCode
January 13, 2026 - If you’re using Jetpack Compose, you can still use FusedLocationProviderClient and trigger it from a button click; just remember that your state updates need to be managed properly to avoid re‑requests on recomposition. ... Keep a mutableStateOf for the location string. Trigger the location call only from explicit user actions. Use rememberLauncherForActivityResult for permissions. If your app requires location while in the background, Android requires additional permission and often a foreground service.