无法在Google Map API上获取我的位置

时间:2018-08-11 17:07:53

标签: android google-maps

我一直试图让Google地图显示我的当前位置,但这只是显示整个地图。请我怎么做,这是我的代码

 @Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

    if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){

        }else{
            checkLocationPermission();
        }
    }

    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
    mMap.setMyLocationEnabled(true);
}

private void checkLocationPermission() {
    if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
            new android.app.AlertDialog.Builder(this)
                    .setTitle("give permission")
                    .setMessage("give permission message")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ActivityCompat.requestPermissions(WorkerMap.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
                        }
                    })
                    .create()
                    .show();
        }
        else{
            ActivityCompat.requestPermissions(WorkerMap.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }
    }
}
LocationCallback mLocationCallback = new LocationCallback(){
    @Override
    public void onLocationResult(LocationResult locationResult) {
        for(Location location : locationResult.getLocations()){
            if(getApplicationContext()!=null){
                mLastLocation = location;

                LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());

                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
            }
        }
    }
};

应该可以找到我当前的位置,但是没有这样做。请问可能有什么问题

1 个答案:

答案 0 :(得分:0)

1)您必须致电

mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);

之后,您将获得用户的许可,例如在功能onRequestPermissionsResult中。

2)尝试使用mFusedLocationClient.getLastLocation(),然后再提出请求。

3)您在哪个设备上测试此代码?