62

I've looked high and low for an answer on this, and no one, in any forum question has been able to help. I've searched through the tutorials. The API Guide says:

The My Location button appears in the top right corner of the screen only when the My Location layer is enabled.

So I've been looking for this My Location layer and have been unable to find anything. How do I show my location on a Google Map?

Yos233
  • 2,396
  • 2
  • 15
  • 15
  • There are several other questions about finding current location on Google Maps Android V2 on SO. With that said, here is a solution that will enable location as well as allow you to react to location changes: http://stackoverflow.com/a/13753518/1103584 – DiscDev Feb 28 '13 at 20:35
  • Thanks for the link. I had already figured out how to access the GPS, and center the map on the user. The API guide came through there. I was looking for the specific piece of code that shows the user's location on the map as the blue dot. – Yos233 Mar 01 '13 at 05:07

6 Answers6

157

The API Guide has it all wrong (really Google?). With Maps API v2 you do not need to enable a layer to show yourself, there is a simple call to the GoogleMaps instance you created with your map.

Google Documentation

The actual documentation that Google provides gives you your answer. You just need to

If you are using Kotlin

// map is a GoogleMap object
map.isMyLocationEnabled = true


If you are using Java

// map is a GoogleMap object
map.setMyLocationEnabled(true);

and watch the magic happen.

Just make sure that you have location permission and requested it at runtime on API Level 23 (M) or above

Leonardo Sibela
  • 1,613
  • 1
  • 18
  • 39
Yos233
  • 2,396
  • 2
  • 15
  • 15
  • 10
    Is there any method to auto click on the MyLocationButton to center the map? Now I have to use LocationClient to do the same what the MyLocationButton do. – iForests Jun 15 '13 at 13:02
  • I do not believe there is a way to programmatically call the MyLocation button. However, you can use a LocationManager object. – Yos233 Jun 16 '13 at 15:19
  • Then you can use a CameraPosition object to move the map to wherever you like. – Yos233 Jun 16 '13 at 15:25
  • Thank you so much for your answer. I've a continuation question. By default, my location button is shown at the top right. How can show the layer at the bottom right? Can you help? – Srikar Reddy Jun 17 '16 at 09:40
  • Similar problem here. How can I move or add some margin to the my location button? – Akronix Dec 24 '17 at 19:52
  • I found the solution! Just add some padding to the map as said here: https://stackoverflow.com/questions/14489880/change-position-of-google-maps-apis-my-location-button – Akronix Dec 24 '17 at 20:06
  • Is it possible to increase the size of this icon? – Sethuraman Srinivasan Jan 14 '19 at 07:43
40

Java code:

public class MapActivity extends FragmentActivity implements LocationListener  {

    GoogleMap googleMap;
    LatLng myPosition;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        // Getting reference to the SupportMapFragment of activity_main.xml
        SupportMapFragment fm = (SupportMapFragment)
        getSupportFragmentManager().findFragmentById(R.id.map);

        // Getting GoogleMap object from the fragment
        googleMap = fm.getMap();

        // Enabling MyLocation Layer of Google Map
        googleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            // Getting latitude of the current location
            double latitude = location.getLatitude();

            // Getting longitude of the current location
            double longitude = location.getLongitude();

            // Creating a LatLng object for the current location
            LatLng latLng = new LatLng(latitude, longitude);

            myPosition = new LatLng(latitude, longitude);

            googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
        }
    }
}

activity_map.xml:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:map="http://schemas.android.com/apk/res-auto"
  android:id="@+id/map"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  class="com.google.android.gms.maps.SupportMapFragment"/>

You will get your current location in a blue circle.

rmtheis
  • 5,992
  • 12
  • 61
  • 78
UdiT
  • 609
  • 1
  • 6
  • 21
  • Thank you UdiT, looks very nice. But what do you do with your `latLing` variable? This code shows it is not in use. Thx. – Azurespot Dec 29 '14 at 22:34
  • Ah, nevermind, I guess that 2 LatLng objects are not needed, so I deleted one and used myPosition instead. It worked! Thanks again! – Azurespot Dec 29 '14 at 22:41
  • The code perfectly shows the current location but the map is very much zoomed out. How to set the default zoom level which you see when you start google map? – BTR Naidu Dec 28 '15 at 10:57
  • 1
    @BTRNaidu Well, you have to make a camera trasition like this :CameraPosition cameraPosition = new CameraPosition.Builder().target(location).zoom(16).build(); googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); – Copacel Nov 11 '16 at 22:10
  • please add request permission to you code to complete – roghayeh hosseini Apr 23 '19 at 10:49
19

From android 6.0 you need to check for user permission, if you want to use GoogleMap.setMyLocationEnabled(true) you will get Call requires permission which may be rejected by user error

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
   mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}

if you want to read more, check google map docs

Vasil Valchev
  • 5,701
  • 2
  • 34
  • 39
18

To show the "My Location" button you have to call

map.getUiSettings().setMyLocationButtonEnabled(true);

on your GoogleMap object.

FabioLor
  • 189
  • 4
  • 2
    But first the map needs to show the user location. That is what I was asking about. The button is no good if there is no blue dot. – Yos233 Mar 01 '13 at 05:04
  • 2
    If you're using MapView then: map.setMyLocationEnabled(true); map.getUiSettings().setMyLocationButtonEnabled(true); both need to be written – Bam Oct 26 '14 at 13:28
7

Call GoogleMap.setMyLocationEnabled(true) in your Activity, and add this 2 lines code in the Manifest:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
pinckerman
  • 4,115
  • 6
  • 33
  • 42
Terranology
  • 610
  • 9
  • 15
2

Before enabling the My Location layer, you must request location permission from the user. This sample does not include a request for location permission.

To simplify, in terms of lines of code, the request for the location permit can be made using the library EasyPermissions.

Then following the example of the official documentation of The My Location Layer my code works as follows for all versions of Android that contain Google services.

  1. Create an activity that contains a map and implements the interfaces OnMyLocationClickListener y OnMyLocationButtonClickListener.
  2. Define in app/build.gradle implementation 'pub.devrel:easypermissions:2.0.1'
  3. Forward results to EasyPermissions within method onRequestPermissionsResult()

    EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

  4. Request permission and operate according to the user's response with requestLocationPermission()

  5. Call requestLocationPermission() and set the listeners to onMapReady().

MapsActivity.java

public class MapsActivity extends FragmentActivity implements 
    OnMapReadyCallback,
    GoogleMap.OnMyLocationClickListener,
    GoogleMap.OnMyLocationButtonClickListener {

    private final int REQUEST_LOCATION_PERMISSION = 1;

    private GoogleMap mMap;

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

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

        requestLocationPermission();
        mMap.setOnMyLocationButtonClickListener(this);
        mMap.setOnMyLocationClickListener(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @SuppressLint("MissingPermission")
    @AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
    public void requestLocationPermission() {
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if(EasyPermissions.hasPermissions(this, perms)) {
            mMap.setMyLocationEnabled(true);
            Toast.makeText(this, "Permission already granted", Toast.LENGTH_SHORT).show();
        }
        else {
            EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
        }
    }

    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {
        Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
    }
}

Source

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62