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

前端 未结 13 1088
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:14

    Ensure that you have turned ON the location services on the device. Else you won't get any location related info.

    This works for me,

        map = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
        map.setMyLocationEnabled(true);
        GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange (Location location) {
               LatLng loc = new LatLng (location.getLatitude(), location.getLongitude());
               map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
            }
        };
        map.setOnMyLocationChangeListener(myLocationChangeListener);
    

    }

    0 讨论(0)
  • 2020-11-27 13:16

    To get the location when the user clicks on a button call this method in the onClick-

    void getCurrentLocation() {
        Location myLocation  = mMap.getMyLocation();
        if(myLocation!=null)
        {
            double dLatitude = myLocation.getLatitude();
            double dLongitude = myLocation.getLongitude();
            Log.i("APPLICATION"," : "+dLatitude);
            Log.i("APPLICATION"," : "+dLongitude);
            mMap.addMarker(new MarkerOptions().position(
                    new LatLng(dLatitude, dLongitude)).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(Utils.getBitmap("pointer_icon.png"))));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));
    
        }
        else
        {
            Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
        }
    
    }
    

    Also make sure that the

    setMyLocationEnabled

    is set to true.

    Try and see if this works...

    0 讨论(0)
  • 2020-11-27 13:17

    try this

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
        mMap.setMyLocationEnabled(true);
    } else {
        // Show rationale and request permission.
    }
    
    0 讨论(0)
  • 2020-11-27 13:20

    try this

    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = service.getBestProvider(criteria, false);
    Location location = service.getLastKnownLocation(provider);
    LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
    
    0 讨论(0)
  • 2020-11-27 13:20

    the accepted answer works but some of the used methods are now deprecated so I think it is best if I answer this question with updated methods.

    this is answer is completely from this guide on google developers

    so here is step by step guide:

    1. implement all this in your map activity

      MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks

    2. in your onCreate:

      private GoogleMap mMap;
      private Context context;
      private TextView txtStartPoint,txtEndPoint;
      private GoogleApiClient mGoogleApiClient;
      private Location mLastKnownLocation;
      private LatLng mDefaultLocation;
      private CameraPosition mCameraPosition;
      private boolean mLocationPermissionGranted;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_maps);
      context = this;
      mGoogleApiClient = new GoogleApiClient.Builder(this)
              .enableAutoManage(this /* FragmentActivity */,
                      this /* OnConnectionFailedListener */)
              .addConnectionCallbacks(this)
              .addApi(LocationServices.API)
              .addApi(Places.GEO_DATA_API)
              .addApi(Places.PLACE_DETECTION_API)
              .build();
      mGoogleApiClient.connect();
      }
      
    3. in your onConnected :

      SupportMapFragment mapFragment = (SupportMapFragment)     getSupportFragmentManager()
              .findFragmentById(map);
      mapFragment.getMapAsync(this);
      
    4. in your onMapReady :

      @Override
      public void onMapReady(GoogleMap googleMap) {
      mMap = googleMap;
      
      // Do other setup activities here too, as described elsewhere in this tutorial.
      
      // Turn on the My Location layer and the related control on the map.
      updateLocationUI();
      
      // Get the current location of the device and set the position of the map.
      getDeviceLocation();
      }
      
    5. and these two are methods in onMapReady :

      private void updateLocationUI() {
        if (mMap == null) {
          return;
      }
      
      if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
              android.Manifest.permission.ACCESS_FINE_LOCATION)
              == PackageManager.PERMISSION_GRANTED) {
          mLocationPermissionGranted = true;
      }
      
      if (mLocationPermissionGranted) {
          mMap.setMyLocationEnabled(true);
          mMap.getUiSettings().setMyLocationButtonEnabled(true);
      } else {
          mMap.setMyLocationEnabled(false);
          mMap.getUiSettings().setMyLocationButtonEnabled(false);
          mLastKnownLocation = null;
      }
      }
      
      private void getDeviceLocation() {
      if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
              android.Manifest.permission.ACCESS_FINE_LOCATION)
              == PackageManager.PERMISSION_GRANTED) {
          mLocationPermissionGranted = true;
      }
      
      if (mLocationPermissionGranted) {
          mLastKnownLocation = LocationServices.FusedLocationApi
                  .getLastLocation(mGoogleApiClient);
      }
      
      // Set the map's camera position to the current location of the device.
      float DEFAULT_ZOOM = 15;
      if (mCameraPosition != null) {
          mMap.moveCamera(CameraUpdateFactory.newCameraPosition(mCameraPosition));
      } else if (mLastKnownLocation != null) {
          mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                  new LatLng(mLastKnownLocation.getLatitude(),
                          mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
      } else {
          Log.d("pouya", "Current location is null. Using defaults.");
          mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
          mMap.getUiSettings().setMyLocationButtonEnabled(false);
      }
      }
      

    this is very fast , smooth and effective. hope this helps

    0 讨论(0)
  • 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.

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