【发布时间】:2016-03-01 06:28:17
【问题描述】:
我试图在地图活动中标记当前用户位置,但 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 的连接性时,它始终未连接
【问题讨论】:
-
在调用
onConnected()之前不要尝试调用getLastLocation(),而不是更早。 -
它不起作用但它根本不准确,有什么建议吗?
-
好吧,您似乎只有粗略的位置权限。应该是不准确的此外,
getLastKnownLocation()没有具体说明质量方面的任何内容,因此它可能专门使用低功耗方法。 -
那我还能用什么? FINELocation 权限?
标签: android