79

I'm trying to mess around with the Maps API V2 to get more familiar with it, and I'm trying to start the map centered at the user's current location. Using the map.setMyLocationEnabled(true); statement, I am able to show my current location on the map. This also adds the button to the UI that centers the map on my current location.

I want to simulate that button press in my code. I am familiar with the LocationManager and LocationListener classes and realize that using those is a viable alternative, but the functionality to center and zoom in on the user's location seems to already be built in through the button.

If the API has a method to show the user's current location, there surely must be an easier way to center on the location than to use the LocationManager/LocationListener classes, right?

Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
user139260
  • 987
  • 1
  • 6
  • 10
  • Major point here is to get the geocoordinates of the current location. You can use GPS library to get that. Once you have the geocoordinates, its trivial. Refer the following for more details: https://stackoverflow.com/questions/17519198/how-to-get-the-current-location-latitude-and-longitude-in-android/17519248#17519248 – user846316 Feb 23 '16 at 09:47

10 Answers10

116

Try this coding:

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

    CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
        .zoom(17)                   // Sets the zoom
        .bearing(90)                // Sets the orientation of the camera to east
        .tilt(40)                   // Sets the tilt of the camera to 30 degrees
        .build();                   // Creates a CameraPosition from the builder
    map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));       
}
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
user3161982
  • 1,161
  • 1
  • 7
  • 2
  • 1
    what if the location == null..Please help – jyomin Oct 29 '14 at 04:28
  • @jyomin Check here for my answer of how to get the user location. It uses the above method with a little fail safe to check the next best possible location of the user. http://stackoverflow.com/a/14511032/845038 That might remedy getting a null by checking the next best location. – DMCApps Nov 14 '14 at 21:18
  • 1
    This solution it's simple and just works. Thank you. – Enkk Mar 08 '15 at 15:15
  • This is not working for me on android 4.2.1 but working on my nexus 7 tablet with android 5. could you please help on this? – farid bekran Nov 08 '16 at 17:53
  • `The Google Play services location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app.` This method is old. Please check https://developer.android.com/training/location/index.html – Gokhan Arik Oct 08 '17 at 21:32
45

After you instansiated the map object (from the fragment) add this -

private void centerMapOnMyLocation() {

    map.setMyLocationEnabled(true);

    location = map.getMyLocation();

    if (location != null) {
        myLocation = new LatLng(location.getLatitude(),
                location.getLongitude());
    }
    map.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
            Constants.MAP_ZOOM));
}

if you need any guidance just ask but it should be self explantory - just instansiate the myLocation object for a default one...

crazyPixel
  • 2,301
  • 5
  • 24
  • 48
  • 1
    I have the same problem, but when I try to use map.getMyLocation() it warns me that this method is deprecated. What would be the right way to do it now? – Pam Nov 27 '13 at 21:24
  • 15
    "getMyLocation() This method is deprecated. use LocationClient instead. LocationClient provides improved location finding and power usage and is used by the "My Location" blue dot. See the MyLocationDemoActivity in the sample applications folder for example example code, or the Location Developer Guide." (taken from the android developer site) Next time just read the API if something got deprecated there is a replacement for it – crazyPixel Nov 28 '13 at 14:03
  • 5
    LocationClient has been marked obsolete. You have to use LocationServices instead – Lars Nielsen Jul 23 '14 at 19:03
  • I guess Constants.MAP_ZOOM is supposed to be the Zoom level defined by us? – AgentKnopf Aug 31 '14 at 19:25
  • @Zainodis you are guessing right. As a thumb rule whenever I write something that is dependent on some previous data or on a data that should be acquired I initiate it for some default value. – crazyPixel Sep 01 '14 at 09:02
  • what if the location == null..Please help – jyomin Oct 29 '14 at 04:29
  • @jyomin in this case try and get it from the device gps/3g last known location write it as an external method. – crazyPixel Oct 29 '14 at 19:35
  • http://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.html getMyLocation() This method is deprecated. use FusedLocationProviderApi instead. Answer edited – Marian Paździoch Feb 18 '15 at 10:38
  • Everything is being deprecated! – Eduardo Oct 24 '15 at 20:14
21
youmap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentlocation, 16));

16 is the zoom level

Smern
  • 18,746
  • 21
  • 72
  • 90
SHASHIDHAR MANCHUKONDA
  • 3,302
  • 2
  • 19
  • 40
  • 1
    But how do I get currentLocation without using the LocationManager and LocationListener? Or is that not possible? – user139260 Aug 25 '13 at 04:05
  • it is not possible as per my knowledge. and i am suggesting you not to use location manager . user Location client which is of high accuarcy and low battery power consumption and easy to implement.http://developer.android.com/google/play-services/location.html newly launched by google – SHASHIDHAR MANCHUKONDA Aug 25 '13 at 04:24
  • 1
    Location location = map.getMyLocation(); map is GoogleMap object – Venkat Sep 26 '13 at 04:16
  • instead of 16 you can use 14.0f – Däñish Shärmà Jun 10 '16 at 12:17
16
    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {

                CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
                mMap.moveCamera(center);
                mMap.animateCamera(zoom);

        }
    });
mz87
  • 1,398
  • 2
  • 13
  • 13
10

try this code :

private GoogleMap mMap;


LocationManager locationManager;


private static final String TAG = "";

@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(map);
    mapFragment.getMapAsync(this);

    arrayPoints = new ArrayList<LatLng>();
}

@Override
public void onMapReady(GoogleMap googleMap) {


    mMap = googleMap;


    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);


    LatLng myPosition;


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
    }
    googleMap.setMyLocationEnabled(true);
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location location = locationManager.getLastKnownLocation(provider);


    if (location != null) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        LatLng latLng = new LatLng(latitude, longitude);
        myPosition = new LatLng(latitude, longitude);


        LatLng coordinate = new LatLng(latitude, longitude);
        CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 19);
        mMap.animateCamera(yourLocation);
    }
}

}

Dont forget to add permissions on AndroidManifest.xml.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Gustavo
  • 111
  • 1
  • 2
  • 1
    Welcome to Stack Overflow! While this piece of code may answer the question, it is better to include a description of what the problem was, and how your code will tackle the given problem. For the future, here is some information, how to crack a awesome answer on Stack Overflow: http://stackoverflow.com/help/how-to-answer – dirtydanee Dec 19 '16 at 15:32
5

Here's how to do it inside ViewModel and FusedLocationProviderClient, code in Kotlin

locationClient.lastLocation.addOnSuccessListener { location: Location? ->
            location?.let {
                val position = CameraPosition.Builder()
                        .target(LatLng(it.latitude, it.longitude))
                        .zoom(15.0f)
                        .build()
                map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
            }
        }
onmyway133
  • 45,645
  • 31
  • 257
  • 263
  • Is that advisable? Chainging multiple items like `locationClient.lastLocation.addOnSuccessListener{}`? – Gilbert May 16 '20 at 17:51
4
private void setUpMapIfNeeded(){
    if (mMap == null){
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();//invoke of map fragment by id from main xml file

     if (mMap != null) {
         mMap.setMyLocationEnabled(true);//Makes the users current location visible by displaying a blue dot.

         LocationManager lm=(LocationManager)getSystemService(LOCATION_SERVICE);//use of location services by firstly defining location manager.
         String provider=lm.getBestProvider(new Criteria(), true);

         if(provider==null){
             onProviderDisabled(provider);
              }
         Location loc=lm.getLastKnownLocation(provider);


         if (loc!=null){
             onLocationChanged(loc);
      }
         }
     }
}

    // Initialize map options. For example:
    // mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

@Override
public void onLocationChanged(Location location) {

   LatLng latlng=new LatLng(location.getLatitude(),location.getLongitude());// This methods gets the users current longitude and latitude.

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));//Moves the camera to users current longitude and latitude
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latlng,(float) 14.6));//Animates camera and zooms to preferred state on the user's current location.
}

    // TODO Auto-generated method stub

imm3000
  • 61
  • 2
  • Please add some explanation of what your code does and how it answers the question, and please format it properly. Convert tabs to spaces before copying code to SO, because tabs often don't get rendered as expected. – Adi Inbar Apr 12 '14 at 03:24
  • The above solution loads up a map fragment, and shows a centred position of the users current location using the desired zoom level in this case mine was (14.6)@AdiInbar – imm3000 May 05 '14 at 08:26
  • Please include the explanations in the answer rather than responding in comments, and format the code. (FYI, I didn't ask out of personal interest. I encountered your answer in the Low Quality Posts review queue and was advising you to improve it to avoid further downvotes and delete votes.) – Adi Inbar May 05 '14 at 14:28
3

check this out:

    fun requestMyGpsLocation(context: Context, callback: (location: Location) -> Unit) {
        val request = LocationRequest()
        //        request.interval = 10000
        //        request.fastestInterval = 5000
        request.numUpdates = 1
        request.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        val client = LocationServices.getFusedLocationProviderClient(context)

        val permission = ContextCompat.checkSelfPermission(context,
            Manifest.permission.ACCESS_FINE_LOCATION )
        if (permission == PackageManager.PERMISSION_GRANTED) {
            client.requestLocationUpdates(request, object : LocationCallback() {
                override fun onLocationResult(locationResult: LocationResult?) {
                val location = locationResult?.lastLocation
                if (location != null)
                    callback.invoke(location)
            }
         }, null)
       }
     }

and

    fun zoomOnMe() {
        requestMyGpsLocation(this) { location ->
            mMap?.animateCamera(CameraUpdateFactory.newLatLngZoom(
                LatLng(location.latitude,location.longitude ), 13F ))
        }
    }
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
2

This is working Current Location with zoom for Google Map V2

 double lat= location.getLatitude();
 double lng = location.getLongitude();
 LatLng ll = new LatLng(lat, lng);
 googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Shreyans Patel
  • 129
  • 1
  • 10
0

In kotlin, you will get the current location then move the camera like this

map.isMyLocationEnabled = true
fusedLocationClient.lastLocation
    .addOnSuccessListener { location: Location? ->
        if (location != null) {
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 14f))
        }
    }

Also you can animate the move by using this function instead

map.animateCamera(CameraUpdateFactory.newLatLngZoom(LatLng(location.latitude, location.longitude), 14f))
Marawan Mamdouh
  • 584
  • 1
  • 6
  • 15