Java 显示位置和将摄像头置于其中心时出现问题
我刚刚在CameraUpdate工厂遇到了一些奇怪的问题 因此,我将此代码合并到导航片段上GpsButton上的onclickListener中:Java 显示位置和将摄像头置于其中心时出现问题,java,android,google-maps,geolocation,locationmanager,Java,Android,Google Maps,Geolocation,Locationmanager,我刚刚在CameraUpdate工厂遇到了一些奇怪的问题 因此,我将此代码合并到导航片段上GpsButton上的onclickListener中: if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
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按钮时才能在地图上显示为蓝点。到目前为止,这是一个完美的功能
我还采用了一种方法将相机移动到当前位置:
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 这可以在不启动提供程序的情况下完成。请注意,此位置可能已过期,例如,如果设备已关闭并移动到其他位置。 如果提供程序当前已禁用,则返回null 如果要检索用户的当前文档,必须使用requestLocation更新。
我明白了,但其中一个问题似乎是,它正确地获取了我的位置,然后显示了我的位置,即我已经回来一个小时了。这正常吗?位置有时是正确的,有时是错误的,这是正常的。如果另一个应用程序最近没有请求位置,则您的位置可能已过时,其他时候它将是正确的。但是,如果您的位置正确,通常几分钟后也应该正确。您应该记录使用了哪个Locationprovider,因为您使用的是getBestLocationProvider,它可能会在每次调用此方法时返回不同的Locationprovider,准确度可能会更高或更低,因此会出现不同的位置。有没有办法通过编程在Google地图上锁定摄像头。setmyLocationEnabled?如果使用setmyLocationEnabled,我认为地图已经以用户当前位置为中心。你可能会在这个网站上找到类似的问题,或者你应该创建一个新的问题。如果我的回答回答了你最初的问题,请将其标记为已接受。解决它。setMyLocationEnabled仅显示当前位置,不居中。有一种方法可以调用UI按钮,但无法通过编程访问该按钮。谢谢你的帮助:)