how to get current location in google map android

前端 未结 17 1931
长发绾君心
长发绾君心 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:48

    This Code in MapsActivity Class works for me :

    public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    
    private GoogleMap mMap;
    LocationManager locationManager;
    LocationListener locationListener;
    
    public void centreMapOnLocation(Location location, String title){
    
        LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
        mMap.clear();
        mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation,12));
    
    }
    
    @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);
    
                Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                centreMapOnLocation(lastKnownLocation,"Your Location");
            }
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps2);
        // 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;
    
        Intent intent = getIntent();
        if (intent.getIntExtra("Place Number",0) == 0 ){
    
            // Zoom into users location
            locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
            locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    centreMapOnLocation(location,"Your Location");
                }
    
                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {
    
                }
    
                @Override
                public void onProviderEnabled(String s) {
    
                }
    
                @Override
                public void onProviderDisabled(String s) {
    
                }
            };
    
            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);
                    centreMapOnLocation(lastKnownLocation,"Your Location");
            } else {
    
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
            }
        }
    
    
    }
    
    
    }
    
    0 讨论(0)
  • 2020-11-27 14:48
    Location locaton;
    
    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;
        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) {
            return;
        }
    
        mMap.setMyLocationEnabled(true);
    
        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.clear();
    
                MarkerOptions mp = new MarkerOptions();
    
                mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
    
                mp.title("my position");
    
                mMap.addMarker(mp);
                mMap.moveCamera(center);
                mMap.animateCamera(zoom);
    
            }
        });}}
    
    0 讨论(0)
  • 2020-11-27 14:50

    Add the permissions to the app manifest

    Add one of the following permissions as a child of the element in your Android manifest. Either the coarse location permission:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.myapp" >
      ...
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
      ...
    </manifest>
    

    Or the fine location permission:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.myapp" >
      ...
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
      ...
    </manifest>
    

    The following code sample checks for permission using the Support library before enabling the My Location layer:

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    } else {
        // Show rationale and request permission.
    }
    The following sample handles the result of the permission request by implementing the ActivityCompat.OnRequestPermissionsResultCallback from the Support library:
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_LOCATION_REQUEST_CODE) {
          if (permissions.length == 1 &&
              permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
              grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        } else {
          // Permission was denied. Display an error message.
        }
    }
    

    This example provides current location update using GPS provider. Entire Android app code is as follows,

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.widget.TextView;
    
    import android.util.Log;
    
    public class MainActivity extends Activity implements LocationListener{
    protected LocationManager locationManager;
    protected LocationListener locationListener;
    protected Context context;
    TextView txtLat;
    String lat;
    String provider;
    protected String latitude,longitude; 
    protected boolean gps_enabled,network_enabled;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtLat = (TextView) findViewById(R.id.textview1);
    
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    }
    @Override
    public void onLocationChanged(Location location) {
    txtLat = (TextView) findViewById(R.id.textview1);
    txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
    }
    
    @Override
    public void onProviderDisabled(String provider) {
    Log.d("Latitude","disable");
    }
    
    @Override
    public void onProviderEnabled(String provider) {
    Log.d("Latitude","enable");
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    Log.d("Latitude","status");
    }
    }
    
    0 讨论(0)
  • 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);
    
            }
    
    
        }
    
    
        }
    }
    
    0 讨论(0)
  • 2020-11-27 14:53

    All solution mentioned above using that code which are deprecated now!Here is the new solution

    1. Add implementation 'com.google.android.gms:play-services-places:15.0.1' dependency in your gradle file

    2. Add network permission in your manifest file:

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

    1. Now use this code to get current location

        FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
      
        mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
                      @Override
                      public void onSuccess(Location location) {
                          // GPS location can be null if GPS is switched off
                              currentLat = location.getLatitude();
                              currentLong = location.getLongitude();
                              Toast.makeText(HomeNavigationBarActivtiy.this, "lat " + location.getLatitude() + "\nlong " + location.getLongitude(), Toast.LENGTH_SHORT).show();
                      }
                  })
                  .addOnFailureListener(new OnFailureListener() {
                      @Override
                      public void onFailure(@NonNull Exception e) {
                          e.printStackTrace();
                      }
                  });
      
    0 讨论(0)
  • 2020-11-27 14:54
    //check this condition if (Build.VERSION.SDK_INT < 23 ) 
    

    In some android studio it does not work while Whole code is working, so replace this line by this:

    if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
    

    & my project is working fine.

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