mLastLocation:null,始终为null,如何解决?

时间:2020-08-28 04:55:37

标签: android google-maps

mLastLocation:null,始终为null,如何解决?

这是我的代码

private void displayLocation() {
        if(ActivityCompat.checkSelfPermission(TrackingOrder.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(TrackingOrder.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            Log.d("Check-1","ok");
            requestRuntimePermission();
        }
        else
        {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            //mLastLocation = LocationServices.getFusedLocationProviderClient(this).getLastLocation().addOnSuccessListener(mGoogleApiClient);
            Log.d("Check-2","ok");
            Log.d("mLastLocation",String.valueOf(mLastLocation));
            if(mLastLocation != null)
            {

                double latitude = mLastLocation.getLatitude();
                double longitude = mLastLocation.getLongitude();
                Log.d("Check - latitude",String.valueOf(latitude));
                Log.d("Check - longitude",String.valueOf(longitude));

                // Add Marker in your location and move the camera
                LatLng yourLocation = new LatLng(latitude,longitude);
                mMap.addMarker(new MarkerOptions().position(yourLocation).title("Your Location"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(yourLocation));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
                
                //After add marker for your location, add marker for this order and draw route
                drawRoute(yourLocation,Common.currentRequest.getAddress());
                
            }
            else
            {
                Log.d("Error","Cannot get location");
                Toast.makeText(this,"Could'nt get your location", Toast.LENGTH_SHORT).show();
            }
        }
    }

这是我的mGoogleApiClient代码

protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API).build();

        mGoogleApiClient.connect();
    }

但是当我找到该displayLocation函数时,有问题

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

因为mLastLocation仍然为空。

那么我需要在哪里修改?

有完整的代码

https://luvtas.com/gmap.txt

1 个答案:

答案 0 :(得分:0)

在某些情况下,getLastLocation返回null。查看此问题以获取更多信息: LocationClient getLastLocation() return null

您要在模拟器还是物理设备上进行测试?您是否开启了GPS?您具有Manifest.xml中定义的权限吗?

此外,在您的代码中,您正在监听onLocationChanged(Location location)中的位置更新。您正在将新收到的位置存储在mLastLocation中,然后调用displayLocation()。然后,您在mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);中进行displayLocation(),并覆盖从onLocationChanged收到的值。也许不是故意的?

相关问题