15

I'm working with Google Maps in my android app. I need to recenter the map to the client's current location. I used the following statement -

map.setmylocationenabled(true);

This displays a button on the top right but clicking that doesn't work.

The button click listener:

mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
                @Override
                public boolean onMyLocationButtonClick() {
                    mMap.addMarker(new MarkerOptions().position(myLatLng).title("My Location"));
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLatLng, zoomLevel));
                    return false;
                }
            });
Venu Saini
  • 427
  • 2
  • 6
  • 19
  • That just enables the button (It's also enabled by default). You should get the location using the FusedLocationProviderApi, and then move/zoom the map camera to the current position, see here for an example: http://stackoverflow.com/a/34582595/4409409 – Daniel Nugent Jan 05 '16 at 09:55
  • Try to set marker on that location and then you will get click event of marker. – Kapil Rajput Jan 05 '16 at 09:58
  • @DanielNugent I get the map centred at first launch of the map. The problem comes when I move around the map and want to recentre current location on the screen with that button's click. – Venu Saini Jan 05 '16 at 10:45
  • @VenuSaini Show your current button click listener code – Daniel Nugent Jan 05 '16 at 11:01
  • Oops! I was missing the button click listener. Stupid! Thanks @DanielNugent for your time =] – Venu Saini Jan 05 '16 at 11:11
  • make sure that your GPS is turned on! – Akshay Mahale Mar 06 '17 at 06:55

8 Answers8

12

The last line was a solution for me:

myMap.setMyLocationEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
Andrii Kovalchuk
  • 4,351
  • 2
  • 36
  • 31
5

Just take the code from my other answer here, and modify your button click listener to request another location:

         mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
                @Override
                public boolean onMyLocationButtonClick() {
                     if (mGoogleApiClient != null) {
                         LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                     }
                     return false;
                }
            });

The code in onLocationChanged() will then re-center the camera position, and then un-register for location updates again:

@Override
public void onLocationChanged(Location location)
{
    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }

    //Place current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

    //move map camera
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(11));

    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }
}
Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
  • `onMyLocationButtonClick` in `setOnMyLocationButtonClickListener` don't even call! Neither `com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener()` nor `com.androidmapsextensions.GoogleMap.OnMyLocationButtonClickListener()` – Dr.jacky Aug 07 '17 at 10:40
  • @Mr.Hyde It should work. See here for official documentation: https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.html#setOnMyLocationButtonClickListener(com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener) – Daniel Nugent Aug 07 '17 at 17:08
3

Have you tried to get your latitude and longitude, after using setmylocationenabled(true)?

example

gMap.setMyLocationEnabled(true);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
gMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

you can now use your latitude and longitude, and animate the camera to the lat/lng location that you get.Hope it helps.

Amin Alaee
  • 1,895
  • 17
  • 26
Kristo
  • 1,339
  • 12
  • 22
3

You should add setMyLocationEnabled (boolean enabled) .

Enables or disables the my-location layer.

While enabled and the location is available, the my-location layer continuously draws an indication of a user's current location and bearing, and displays UI controls that allow a user to interact with their location (for example, to enable or disable camera tracking of their location and bearing).

In order to use the my-location-layer feature you need to request permission for either ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION unless you have set a custom location source.

DEMO

You should add this in onMapReady (GoogleMap googleMap) section.

 @Override
        public void onMapReady(GoogleMap googleMap) {

            googleMapOBJ = googleMap;
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            googleMapOBJ.setMyLocationEnabled(true);
            googleMapOBJ.getUiSettings().setMyLocationButtonEnabled(true);
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

Kotlin way

mMap = googleMap
mMap.isMyLocationEnabled = true
mMap.uiSettings.isMyLocationButtonEnabled = true
Aditya Patil
  • 1,287
  • 12
  • 19
1

Kotlin -

mMap!!.isMyLocationEnabled = true
mMap!!.uiSettings.isMyLocationButtonEnabled =  true

Java -

myMap.setMyLocationEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true); 
Kabir
  • 852
  • 7
  • 11
Predator_Shek
  • 71
  • 1
  • 2
0

The location-data layer adds a My Location button to the top-right corner of the map. When the user taps the button the map centers on the device location. The location is shown as a blue dot if the device is stationary and as a blue chevron if the device is moving.

map.setMyLocationEnabled(Boolean) call requires permission and the code should explicitly check to see if permission is available.

Alternatively, you can suppress the missing location permission with an annotation.

You can achieve this easily by using the new Activity Result API

Here is the code

class MapsActivity : AppCompatActivity() , OnMapReadyCallback {

private lateinit var map: GoogleMap


//suppress missing permission
@SuppressLint("MissingPermission")
private val locationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {

    isGranted ->

    if (isGranted) {

        //add my Location Button on top-right side corner
        map.isMyLocationEnabled = true
    }
    else {

        ActivityCompat.requestPermissions(this ,
                arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION) ,
                0)
    }
}

The ActivityResultCallback defines how app handles the user's response to the permission request.

To display the system permissions dialog, call the launch() method on the instance of ActivityResultLauncher.

override fun onMapReady(googleMap: GoogleMap) {
    map = googleMap

    //call launch() passing in the permission required
    locationPermission.launch(Manifest.permission.ACCESS_FINE_LOCATION)}

After launch() is called, the system permissions dialog appears. When the user makes a choice, the system asynchronously invokes implementation of ActivityResultCallback.

Tonnie
  • 4,865
  • 3
  • 34
  • 50
0

I'm getting the same problem in my real device, Even I add permission for Location. Still, It's not working, I just manually turn on the location in my device Its works perfectly.

Ganesh MB
  • 1,109
  • 2
  • 14
  • 27