How to get the current location in Google Maps Android API v2?

前端 未结 13 1164
Happy的楠姐
Happy的楠姐 2020-11-27 12:32

Using

mMap.setMyLocationEnabled(true)

can set the myLocation layer enable.
But the problem is how to get the myLocation when the user

13条回答
  •  囚心锁ツ
    2020-11-27 13:20

    I would rather use FusedLocationApi since OnMyLocationChangeListener is deprecated.

    First declare these 3 variables:

    private LocationRequest  mLocationRequest;
    private GoogleApiClient  mGoogleApiClient;
    private LocationListener mLocationListener;
    

    Define methods:

    private void initGoogleApiClient(Context context)
    {
        mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
        {
            @Override
            public void onConnected(Bundle bundle)
            {
                mLocationRequest = LocationRequest.create();
                mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                mLocationRequest.setInterval(1000);
    
                setLocationListener();
            }
    
            @Override
            public void onConnectionSuspended(int i)
            {
                Log.i("LOG_TAG", "onConnectionSuspended");
            }
        }).build();
    
        if (mGoogleApiClient != null)
            mGoogleApiClient.connect();
    
    }
    
    private void setLocationListener()
    {
        mLocationListener = new LocationListener()
        {
            @Override
            public void onLocationChanged(Location location)
            {
                String lat = String.valueOf(location.getLatitude());
                String lon = String.valueOf(location.getLongitude());
                Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
            }
        };
    
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
    }
    
    private void removeLocationListener()
    {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
    }
    
    • initGoogleApiClient() is used to initialize GoogleApiClient object
    • setLocationListener() is used to setup location change listener
    • removeLocationListener() is used to remove the listener

    Call initGoogleApiClient method to start the code working :) Don't forget to remove the listener (mLocationListener) at the end to avoid memory leak issues.

提交回复
热议问题