how to get current location in google map android

前端 未结 17 1932
长发绾君心
长发绾君心 2020-11-27 14:04

Actually my problem is I am not getting current location latitude and longitude I tried so many ways.I know that this question already asked in SO I tried that answers also

相关标签:
17条回答
  • 2020-11-27 14:56
    1. Select google map activity

    2. you need a Google Maps API key.

      To get one, follow this link, follow the directions and press "Create" at the end: https://console.developers.google.com/flows/enableapi?apiid=maps_android_backend&keyType=CLIENT_SIDE_ANDROID&r=48:C7:A8:5B:31:4F:78:F2:38:41:97:F4:70:C3:A0:EB:6A:73:28:88%3Bcom.example.myapplication

    3. Paste this Code in MapsActivity.java

    import android.Manifest;
    import android.content.pm.PackageManager;
    import android.location.Location;
    import android.os.Build;
    
    import android.os.Bundle;
    
    import android.widget.Toast;
    
    import androidx.core.app.ActivityCompat;
    import androidx.core.content.ContextCompat;
    import androidx.fragment.app.FragmentActivity;
    
    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    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.BitmapDescriptorFactory;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.google.android.gms.maps.model.MarkerOptions;
    
    
    
      public class MapsActivity extends FragmentActivity implement
       OnMapReadyCallback,
       GoogleApiClient.ConnectionCallbacks,
       GoogleApiClient.OnConnectionFailedListener,
      LocationListener{
    
        @private GoogleMap mMap;
            GoogleApiClient mGoogleApiClient;
            Location mLastLocation;
            Marker mCurrLocationMarker;
            LocationRequest mLocationRequest;
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_maps);
    
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    checkLocationPermission();
                }
                // 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;
    
    
                //Initialize Google Play Services
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION) ==
                        PackageManager.PERMISSION_GRANTED) {
                        buildGoogleApiClient();
                        mMap.setMyLocationEnabled(true);
                    }
                } else {
                    buildGoogleApiClient();
                    mMap.setMyLocationEnabled(true);
                }
            }
    
            protected synchronized void buildGoogleApiClient() {
                mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
                mGoogleApiClient.connect();
            }
    
            @Override
            public void onConnected(Bundle bundle) {
    
                mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(1000);
                mLocationRequest.setFastestInterval(1000);
                mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) ==
                    PackageManager.PERMISSION_GRANTED) {
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
                }
    
            }
    
            @Override
            public void onConnectionSuspended(int i) {
    
            }
    
            @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 = mMap.addMarker(markerOptions);
    
                //move map camera
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    
                //stop location updates
                if (mGoogleApiClient != null) {
                    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                }
    
            }
    
            @Override
            public void onConnectionFailed(ConnectionResult connectionResult) {
    
            }
    
            public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
            public boolean checkLocationPermission() {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED) {
    
                    // Asking user if explanation is needed
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)) {
    
                        // Show an explanation to the user *asynchronously* -- don't block
                        // this thread waiting for the user's response! After the user
                        // sees the explanation, try again to request the permission.
    
                        //Prompt the user once explanation has been shown
                        ActivityCompat.requestPermissions(this,
                            new String[] {
                                Manifest.permission.ACCESS_FINE_LOCATION
                            },
                            MY_PERMISSIONS_REQUEST_LOCATION);
    
    
                    } else {
                        // No explanation needed, we can request the permission.
                        ActivityCompat.requestPermissions(this,
                            new String[] {
                                Manifest.permission.ACCESS_FINE_LOCATION
                            },
                            MY_PERMISSIONS_REQUEST_LOCATION);
                    }
                    return false;
                } else {
                    return true;
                }
            }
    
            @Override
            public void onRequestPermissionsResult(int requestCode,
                String permissions[], int[] grantResults) {
                switch (requestCode) {
                    case MY_PERMISSIONS_REQUEST_LOCATION:
                        {
                            // If request is cancelled, the result arrays are empty.
                            if (grantResults.length > 0 &&
                                grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    
                                // permission was granted. Do the
                                // contacts-related task you need to do.
                                if (ContextCompat.checkSelfPermission(this,
                                        Manifest.permission.ACCESS_FINE_LOCATION) ==
                                    PackageManager.PERMISSION_GRANTED) {
    
                                    if (mGoogleApiClient == null) {
                                        buildGoogleApiClient();
                                    }
                                    mMap.setMyLocationEnabled(true);
                                }
    
                            } else {
    
                                // Permission denied, Disable the functionality that depends on this permission.
                                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                            }
                            return;
                        }
    
    
                }
            }
        }
    
    1. Make sure these permission are written in Manifest file

      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    2. Add following dependencies

      implementation 'com.google.android.gms:play-services-maps:17.0.0'

      implementation 'com.google.android.gms:play-services-location:17.0.0'

    0 讨论(0)
  • 2020-11-27 14:57
    public class MainActivity extends ActionBarActivity implements
        ConnectionCallbacks, OnConnectionFailedListener {
    ...
    @Override
    public void onConnected(Bundle connectionHint) {
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
            mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
        }
    }
    }
    
    0 讨论(0)
  • 2020-11-27 14:58
             import android.Manifest;
    import android.content.pm.PackageManager;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.os.Build;
    import android.os.Bundle;
    
    import androidx.annotation.RequiresApi;
    import androidx.core.app.ActivityCompat;
    import androidx.fragment.app.FragmentActivity;
    
    import com.google.android.gms.location.FusedLocationProviderClient;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationServices;
    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;
    import com.google.android.gms.tasks.OnSuccessListener;
    
    import java.io.IOException;
    import java.util.List;
    import java.util.Locale;
    
    import static android.Manifest.permission.ACCESS_FINE_LOCATION;
    
    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
    
        private GoogleMap mMap;
        private FusedLocationProviderClient client;
        double latit;
        double longi;
    
        @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);
            client = LocationServices.getFusedLocationProviderClient(this);
        }
    @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
    
    
    
            try {
                setupMap();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
     client = LocationServices.getFusedLocationProviderClient(this);
    
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#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 Activity#requestPermissions for more details.
                return;
            }
            client.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
    
                                //    local=findViewById(R.id.tv5);
    
                                double la=location.getLatitude();
                                double lo=location.getLongitude();
    
                                LatLng curre=new LatLng(la,lo);
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curre,18));
    
                            }
                        }
                    });
    
    
    
        }
        }
    
    0 讨论(0)
  • 2020-11-27 14:59

    Your current location might not be available immediately, after the map fragment is initialized.

    After set

    googleMap.setMyLocationEnabled(true);
    

    you have to wait until you see the blue dot shown on your MapView. Then

    Location myLocation = googleMap.getMyLocation();
    

    myLocation won't be null.

    I think you better use the LocationClient instead, and implement your own LocationListener.onLocationChanged(Location l)

    Receiving Location Updates will show you how to get current location from LocationClient

    0 讨论(0)
  • 2020-11-27 15:00

    Please check the sample code for the Google Maps Android API v2. Using this will solve your problem.

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
            mMap.setMyLocationEnabled(true);
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                    @Override
                    public void onMyLocationChange(Location arg0) {
                        mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("It's Me!"));
                    }
                });
            }
        }
    }
    

    Call this function in onCreate function.

    0 讨论(0)
提交回复
热议问题