如何更新实时数据库的当前位置经度和纬度

时间:2018-05-24 20:31:58

标签: android firebase dictionary firebase-realtime-database location

我使用 FusedLocationProviderClient `来获取当前的设备位置

com.google.android.gms.tasks.Task<Location> location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull com.google.android.gms.tasks.Task<Location> task) {
                        if(task.isSuccessful()){
                            Location currentLocation = task.getResult();

                            Toast.makeText(getApplicationContext(),"Detecting current Location",Toast.LENGTH_LONG).show();

                            moveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),ZOOM,"My Location");


                            mUserLocalStore = new UserLocalStore(getApplicationContext());
                            db = FirebaseDatabase.getInstance();
                            mRef = db.getReference("Location");
                            mRef.setValue(String.valueOf(mUserLocalStore.getDetails().getEmail()+" "+currentLocation.getLatitude()+" ,"+String.valueOf(currentLocation.getLongitude())));

并在firebase中保存位置,如何在更改位置时更新位置到firebase,或者给予时间段`

1 个答案:

答案 0 :(得分:0)

检查这个小例子,它应该可以解决你的问题。请检查onConnected()方法,有你需要的逻辑,如果你需要,我也会让你所有的代码一起工作:

 package current_location_to_firebase.mytrendin.com.currentlocation;


    import android.location.Location;
    import android.os.Bundle;

    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    import android.widget.Toast;

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;


    public class MainActivity extends AppCompatActivity implements
            ConnectionCallbacks, OnConnectionFailedListener {

        private static final String TAG = "CurrentLocationApp";
        private GoogleApiClient mGoogleApiClient;
        private Location mLastLocation;
        private TextView mLatitudeText;
        private TextView mLongitudeText;
        private FirebaseDatabase mFirebaseDatabase;
        private DatabaseReference mLocationDatabaseReference;
        Button saveLocationToFirebase;
        String value_lat = null;
        String value_lng=null;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            FirebaseApp.initializeApp(this);
            mFirebaseDatabase = FirebaseDatabase.getInstance();
            mLocationDatabaseReference= mFirebaseDatabase.getReference().child("my current location");
            mLatitudeText = (TextView) findViewById((R.id.latitude_text));
            mLongitudeText = (TextView) findViewById((R.id.longitude_text));
            saveLocationToFirebase=(Button)findViewById(R.id.save_location);
            buildGoogleApiClient();
        }

        protected synchronized void buildGoogleApiClient() {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }

        @Override
        protected void onStart() {
            super.onStart();
            mGoogleApiClient.connect();
        }

        @Override
        protected void onStop() {
            super.onStop();
            if (mGoogleApiClient.isConnected()) {
                mGoogleApiClient.disconnect();
            }
        }
        @Override
        public void onConnected(Bundle connectionHint) {
            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

                if (mLastLocation != null) {

                            value_lat= String.valueOf(mLastLocation.getLatitude());
                            value_lng =String.valueOf(mLastLocation.getLongitude());
                    mLatitudeText.setText(value_lat);
                    mLongitudeText.setText(value_lng);

                    saveLocationToFirebase.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mLocationDatabaseReference.push().setValue("Latitude : "+value_lat +"  &amp; Longitude : "+value_lng);
                            Toast.makeText(MainActivity.this ,"Location saved to the Firebasedatabase",Toast.LENGTH_LONG).show();
                        }
                    });
                }
        }
        @Override
        public void onConnectionFailed(ConnectionResult result) {
            Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
        }
         @Override
        public void onConnectionSuspended(int cause) {
            Log.i(TAG, "Connection suspended");
            mGoogleApiClient.connect();
        }

    }

请记住,在您的数据库规则中将它们设置为true,如果它们被设置为false,只让auth用户发布到其中

enter image description here

saveLocationToFirebase 是一个应该在XML中初始化的按钮,因此当我们单击它时,您将值更新到数据库,如果您希望它们自己执行,请将监听器附加到纬度和经度,所以,当他们改变它时会提示上传到数据库。