我一直在努力解决这个问题,目前唯一的解决办法就是使用
fuse location client
检索设备的位置并为“我的位置”按钮添加自定义行为。
通过这种方式,它可以一直工作,而无需重新加载活动。
private void getDeviceLocation() {
/*
* Get the best and most recent location of the device, which may be null in rare
* cases when a location is not available.
*/
try {
if (hasLocationPermission()) {
fusedLocationClient
.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
lastLocation = location;
// Logic to handle location object
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(),
location.getLongitude()), DEFAULT_ZOOM));
mMap.setOnMyLocationButtonClickListener(MapsActivity.this);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
mMap.setMyLocationEnabled(false);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
MapsActivity是GoogleMap.OnMyLocationButtonClickListener链接然后有这个密码
@Override
public boolean onMyLocationButtonClick() {
// I've tried just setting the default behavior of the button, but just works after reloading
// the activity, then I've managed the click event to latest location; now it works for
// all cases.
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lastLocation.getLatitude(),
lastLocation.getLongitude()), DEFAULT_ZOOM));
return false;
}
这是onMapReady的代码
@SuppressLint("MissingPermission")
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
mMap.getUiSettings().setZoomControlsEnabled(true);
getMuseums();
if (!hasLocationPermission()) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSION_LOCATION);
return;
}
getDeviceLocation();
}
我的默认缩放值是10。