如何在开启全球定位系统后获得我的位置

时间:2017-03-03 11:00:06

标签: android google-maps location

我第一次使用谷歌地图,所以PLZ帮助我。我想在打开应用程序时在地图上显示用户位置。当用户已经打开gps时,我已经这样做了。

    LocationManager locationManagerCt = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);

    locationCt = locationManagerCt
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
 LatLng latLng=new LatLng(locationCt.getLatitude(), locationCt.getLongitude());
            MarkerOptions marker = new MarkerOptions().position(latLng).title("Current Location").snippet("Discription");

            marker.icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));

           // Moving Camera to a Location with animation
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(latLng).zoom(15).build();

            HomeActivity.mGoogleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            HomeActivity.mGoogleMap.addMarker(marker);

当gps关闭时。打开Gps后我尝试做同样的事情。 我从这里打开gps: https://stackoverflow.com/a/33555732/3393578

用户开启gps后

   @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (requestCode == 1000) {
     if(resultCode == Activity.RESULT_OK){
         //after user press ok button on GPS popup 

         /*I've apply same code above but unable to get location
          its give me error on Location (nullpointer) */


     } if (resultCode == Activity.RESULT_CANCELED) {
     } 
} 

}

如何在几秒钟内打开GPS后获取位置。 我不想刷新活动。

谢谢!

3 个答案:

答案 0 :(得分:1)

首先,切换到FusedLocationApi而不是现在已经过时的LocationManager。您需要使用FusedLocationAPI的requestLocationUpdates()方法。

浏览google示例了解详情: https://github.com/googlesamples/android-play-location

答案 1 :(得分:0)

请使用此库,这非常有效

https://github.com/mrmans0n/smart-location-lib

答案 2 :(得分:0)

请尝试这样。

    private FusedLocationProviderClient mFusedLocationClient;
    LocationRequest mLocationRequest;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        ButterKnife.bind(this);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}


        public void requestLocationUpdates() {
                mLocationRequest = new LocationRequest();
                mLocationRequest.setInterval(120000); // two minute interval
                mLocationRequest.setFastestInterval(1000);
                mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                }
            }

    @Override
        public void onConnected(Bundle bundle) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#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 ActivityCompat#requestPermissions for more details.
                return;
            }
            requestLocationUpdates();
            mFusedLocationClient.getLastLocation()
                    .addOnCompleteListener(this, new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            if (task.isSuccessful() && task.getResult() != null) {
                                mLastLocation = task.getResult();

                            } else {


                                Log.w(TAG, "getLastLocation:exception", task.getException());
                                Toast.makeText(mContext, "No Location Detected.", Toast.LENGTH_LONG).show();
                            }
                        }
                    });


        }