mLastLocation:null,总是null,怎么解决



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();
}

但是当我定位这个显示位置功能时,出现了问题

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

因为mLastLocation仍然为null。

那么我需要修改哪些地方呢?

有完整的代码

https://luvtas.com/gmap.txt

getLastLocation返回null时,会出现一些边缘情况。查看此问题以获取更多信息:LocationClient getLastLocation((返回空

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

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

相关内容

  • 没有找到相关文章