我试图在地图活动中标记当前用户位置,但是LocationServices.FusedLocationApi.getLastLocation的调用始终返回null
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
private GoogleMap mMap;
private GoogleApiClient mGoogleApiClient=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
protected void onStart() {
if(mGoogleApiClient.isConnected())
Toast.makeText(this,"Client Connect",Toast.LENGTH_SHORT).show();
else
mGoogleApiClient.connect();
super.onStart();
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
LatLng myLocation = null;
if(mLastLocation!=null) {
myLocation = new LatLng(mLastLocation.getLatitude(),
mLastLocation.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myLocation,
mMap.getMaxZoomLevel() - 5));
}
} else {
// Show rationale and request permission.
}
}
}
此外,我已在清单文件中添加了权限
在检查mGoogleApiClient的连接时,它始终没有连接
答案 0 :(得分:2)
您需要为位置事件注册一个监听器,并开始在很短的时间内收听所收到的几个位置,并比较它们的准确性,来源等,以确定哪个是最佳位置,然后使用该位置。
阅读Location strategies google文档,这非常有用,并提供了获取准确位置所需操作的代码示例。
同时将此权限添加到清单:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>