如何根据设备的位置更新数据库列? [英] How to update a database column based on the device's location?

查看:54
本文介绍了如何根据设备的位置更新数据库列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been working on a map based app, and so far the application gets the data of markers from a Room database as a LiveData object and draws the markers on the map and gets the device's location through a FusedLocationProviderClient.

现在,我已经尝试创建一种方法,该方法将在设备到达标记时将数据库中的列从0更新为1,从而使标记处于活动状态".然后,如果标记的活动"标记为敬酒",则将标记的名称显示为祝酒词.列等于1.

Now I have tried to create a method that would update a column in the database from 0 to 1 if the device reaches a marker, making the marker "active" and then displaying the marker's name as a toast if that marker's "active" column equals to 1.

到目前为止,我已经尝试使用 SphericalUtil.computeDistanceBetween(LatLng1,LatLng2)<距离,如果满足条件,则它调用一种方法来更新该列,但由于设备位置不断变化且标记来自LiveData List对象,因此我无法使其正常工作两者都检查了更改,并且我不知道如何在computeDistanceBetween方法中使用这些更改.我浏览了与标记和其他基于地图的对象有关的文档,但到目前为止,我还没有找到解决方案.

So far I have tried to use SphericalUtil.computeDistanceBetween(LatLng1, LatLng2) < distance and if the condition is met, then it calls a method to update the column, but I have not managed to get it to work, as the devices location keeps changing and the markers come from a LiveData List object which are both checked for changes and I don't know how to use these in the computeDistanceBetween method. I have gone through the documents related to markers and other map based objects but so far I have not found a solution.

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

Here is the method that retrieves and draws the markers on the map.

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));
                    }
                }
        }); 

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

the methods that get and draw the device's location on the map.

/**
     * 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);
        }
    }
    

我已经尝试了很多次,但都没有成功,我真的希望有人可以提供帮助,因为我没有想法.任何帮助,我们将不胜感激.另外,我绝不会在任何情况下都寻求帮助,但是我真的很努力,因此,从字面上看,任何有帮助的文档或信息都会很棒.

I have tried to reach a solution for quite a while through many trials but to no success, I really hope someone can help because I am out of ideas. Any help is well appreciated. Also I don't ask for help in just any case but with this I really am struggling, so literally any documentation or piece of info that would help would be great.

推荐答案

这是我以前用来检查位置对象之间的距离的东西,您可以直接使用它,也可以根据需要对其进行修改,代码很漂亮直截了当.

This is something I have previously used to check the distance between location objects, you can use it as it is or modify it to your needs, the code is pretty straight forward.

    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;
    }

要请求位置更新,您需要一个位置请求,然后请求位置更新

To be able to request location updates you need a location Request like so and request location updates

    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());
    }

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

Finally when your activity or fragment pauses make sure to remove/stop the updates like so

        client.removeLocationUpdates(callback)

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

You can find more information on LocarionRequest here, and play around with its configurations, https://developers.google.com/android/reference/com/google/android/gms/location/LocationRequest

这篇关于如何根据设备的位置更新数据库列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆