显示位置并将相机置于其中心的问题

Problems displaying a location and centering the camera on it

由于奇怪的原因,我刚刚遇到了 CameraUpdateFactory 的一些问题。

所以我将这段代码合并到导航片段上 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 按钮时在地图上显示为蓝点。到目前为止,这是完美的功能。

我还采用了一种将相机移动到我当前位置的方法:

 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.

documentation

如果您想检索用户的当前文档,则必须使用 requestLocation 更新。 requestLocationUpdates documentation