how to get current location in google map android

前端 未结 17 1951
长发绾君心
长发绾君心 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条回答
  •  萌比男神i
    2020-11-27 14:50

    Simple steps to get current location on google map:

    1 - create map activity so in onMap ready method you create LocationManager and LocationListener

    2 - in onMap ready also you check for android version and user permission ==> if there is a permission give location update OR ask the user for permission

    3 - in the main class check for result of permission (onRequestPermissionsResult) ==> if the condition is true so give location update

    4 - in (onLocationChanged) method we create LatLng variable and get the coordinates from location then from mMap we (addMarker and moveCamera) for that variable we've just created, this gives us location when the user moves so we still need to create new LatLng in onMap ready to have user's location when the App starts ==>inside condition if there is permission (lastKnownLocation).

    NOTE:

    1) Do Not forget to ask for permissions (Location and Internet) in Manifest

    2) Do Not forget to have Map key from google APIs

    3) We used (mMap.clear) to avoid repeating the marker each time we (run the app or update location)

    Coding Part:

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    
        private GoogleMap mMap;
        LocationManager locationManager;
        LocationListener locationListener;
    
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                }
            }
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_maps);
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
    
    
        }
    
        @SuppressLint("MissingPermission")
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
    
            locationManager  = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    
            locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
    
                    mMap.clear();
    
                    LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
    
                    mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker"));
    
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
    
                    Toast.makeText(MapsActivity.this, userLocation.toString(), Toast.LENGTH_SHORT).show();
                }
    
                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
    
    
                }
    
                @Override
                public void onProviderEnabled(String provider) {
    
                }
    
                @Override
                public void onProviderDisabled(String provider) {
    
                }
    
    
            };
    
            if (Build.VERSION.SDK_INT < 23 ){
    
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    
            }else if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
    
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    
                LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude());
    
                mMap.clear();
    
                mMap.addMarker(new MarkerOptions().position(userLocation).title("Marker"));
    
                mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
    
                Toast.makeText(MapsActivity.this, userLocation.toString(), Toast.LENGTH_SHORT).show();
    
    
            } else {
    
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    
            }
    
    
        }
    
    
        }
    }
    

提交回复
热议问题