由于奇怪的原因,我在使用 CameraUpdateFactory 时遇到了一些问题。
因此,我将此代码合并到导航 fragment 上的 GpsButton 上的 onclickListener 中:
if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
Log.d("Permission checked", "checkSelfPermission passed with no errors");
map.setMyLocationEnabled(true);
Log.d("Permission checked", "Location Layer implementation successful");
} else {
//Request the Permission
ActivityCompat.requestPermissions(mapFragment.getActivity(), new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
这基本上使得仅当按下 GPS 按钮时该位置才会在 map 上显示为蓝点。到目前为止,它的功能非常完善。
我还采用了一种将相机移动到当前位置的方法:
public void locateMe() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE); // Getting LocationManager object from System Service LOCATION_SERVICE
Criteria criteria = new Criteria();// Creating a criteria object to retrieve provider
String provider = locationManager.getBestProvider(criteria, true);// Getting the name of the best provider
if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mapFragment.getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 2);
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude(); //Getting latitude of the current location
double longitude = location.getLongitude(); // Getting longitude of the current location
myPosition = new LatLng(latitude, longitude); // Creating a LatLng object for the current location
map.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, CAMPUS_DEFAULT_ZOOM_LEVEL));//Camera Update method
}
}
出于某种原因,这是偶然的。 3天前,它锁定了一个不是我当前所在位置的位置,而在过去的2天里,它工作得很好。代码没有任何改变。有人可以解释一下发生了什么事吗?任何修复或建议将不胜感激。
最佳答案
出现这种情况是因为您正在使用 getLastKnownLocation。
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location. If the provider is currently disabled, null is returned.
如果您想检索用户的当前文档,则必须使用 requestLocation 更新。 requestLocationUpdates documentation
关于java - 显示位置并将相机置于其中心位置时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42741854/