【问题标题】:How to update a database column based on the device's location?如何根据设备的位置更新数据库列?
【发布时间】:2021-02-12 00:17:48
【问题描述】:

我一直在开发基于地图的应用程序,到目前为止,该应用程序从 Room 数据库中获取标记数据作为 LiveData 对象,并在地图上绘制标记并通过 FusedLocationProviderClient 获取设备的位置。

现在我尝试创建一个方法,如果设备到达标记,则将数据库中的列从 0 更新为 1,使标记“活动”,然后在该标记的“活动”时将标记的名称显示为 toast " 列等于 1。

到目前为止,我已经尝试使用SphericalUtil.computeDistanceBetween(LatLng1, LatLng2) < distance ,如果满足条件,那么它会调用一个方法来更新列,但我没有设法让它工作,因为设备位置不断变化并且标记来自一个 LiveData List 对象,它们都检查了更改,我不知道如何在 computeDistanceBetween 方法中使用它们。我已经浏览了与标记和其他基于地图的对象相关的文档,但到目前为止我还没有找到解决方案。

这是在地图上检索和绘制标记的方法。

markerViewModel.getAllMarkers().observe(this, new Observer<List<MarkerObject>>() {
            @Override
            public void onChanged(List<MarkerObject> markerObjects) {
                for (MarkerObject markerObject : markerObjects) {
                        LatLng latLng = new LatLng(markerObject.getLatitude(), markerObject.getLongitude());
                        mMap.addMarker(new MarkerOptions()
                                .title(markerObject.getTitle())
                                .position(latLng)
                                .visible(true));
                    }
                }
        }); 

获取并在地图上绘制设备位置的方法。

/**
     * Updates the map's UI settings based on whether the user has granted location permission.
     */
    private void updateLocationUI() {
        if (mMap == null) {
            return;
        }
        getLocationPermission();
        try {
            if (locationPermissionGranted) {
                mMap.setMyLocationEnabled(true);
                mMap.getUiSettings().setMyLocationButtonEnabled(true);
            } else {
                mMap.setMyLocationEnabled(false);
                mMap.getUiSettings().setMyLocationButtonEnabled(false);
                lastKnownLocation = null;

            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage());
        }
    }


    /**
     * Gets the current location of the device, and positions the map's camera.
     */
    public 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 (locationPermissionGranted) {
                Task<Location> locationResult = fusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            // Set the map's camera position to the current location of the device.
                            lastKnownLocation = task.getResult();
                            if (lastKnownLocation != null) {
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                        new LatLng(lastKnownLocation.getLatitude(),
                                                lastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                            }
                        } else {
                            Log.d(TAG, "Current location is null. Using defaults.");
                            Log.e(TAG, "Exception: %s", task.getException());
                            mMap.moveCamera(CameraUpdateFactory
                                    .newLatLngZoom(defaultLocation, DEFAULT_ZOOM));
                            mMap.getUiSettings().setMyLocationButtonEnabled(false);
                        }
                    }
                });
            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage(), e);
        }
    }
    

我已经尝试通过多次试验找到解决方案,但没有成功,我真的希望有人能提供帮助,因为我没有想法。任何帮助都将不胜感激。此外,我不会在任何情况下寻求帮助,但我真的很挣扎,所以从字面上看,任何有帮助的文档或信息都会很棒。

【问题讨论】:

    标签: java android google-maps android-room


    【解决方案1】:

    这是我之前用来检查位置对象之间距离的东西,你可以直接使用它,也可以根据需要修改它,代码非常简单。

        public final boolean isLocationCloseEnough(Location currentLocation, Location markerLocation, double distance) {
            // this is where the method stores the distance between the two locations
            float[] distanceInMeters = new float[1];
            Location.distanceBetween(currentLocation.getLatitude(), currentLocation.getLongitude(), markerLocation.getLatitude(), markerLocation.getLongitude(), distanceInMeters);
            return (double)distanceInMeters[0] < distance;
        }
    

    为了能够请求位置更新,您需要这样的位置请求并请求位置更新

        LocationRequest locationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY).setInterval(5);
        LocationCallback callback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                // here is the location
                Location lastLocation = locationResult.getLastLocation();
                // do what needs to be done
            }
        };
    
    
        public void sample() {
            FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(context);
            client.requestLocationUpdates(locationRequest, callback, Looper.getMainLooper());
        }
    

    最后,当您的活动或片段暂停时,请确保像这样删除/停止更新

            client.removeLocationUpdates(callback)
    

    您可以在此处找到有关 LocarionRequest 的更多信息,并尝试其配置,https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest

    【讨论】:

    • 感谢您提供的方法,但我的问题是如果 currentLocation 发生变化,如何获取它。如果我从 getDeviceLocation 返回当前位置,那么它是某一时刻的位置,但是如果 currentLocation 发生变化,我如何不断检查条件?
    • 我编辑了我的答案以显示位置更新
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多