使用android Geofire获取经度和纬度

问题描述 投票:0回答:1

[我正在尝试使用适用于Android的Geo fire来获取用户位置。我试图获取用户的经度和纬度并将其保存在firebase数据库中,但是我没有运气。

下面是我的代码。有人可以告诉我我在做什么错吗?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_after_registration);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
    overridePendingTransition(R.anim.slide_in, R.anim.slide_out);

    savebutton=findViewById(R.id.save);

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    DatabaseReference rootRef =  FirebaseDatabase.getInstance().getReference();
    DatabaseReference update = rootRef.child("Users").child(uid);

    GeoFire geoFire=new GeoFire(rootRef);

    geoFire.getLocation("location", new LocationCallback() {
        @Override
        public void onLocationResult(String key, GeoLocation location) {
            if(location!=null){

                Double longi = location.longitude;
                Double lat = location.latitude;

                update.child("longitude").setValue(longi);
                update.child("latitude").setValue(lat);
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
android firebase firebase-realtime-database geofire
1个回答
1
投票

在GeoFire中,您可以通过字符串键设置和查询位置。要设置键的位置,只需调用setLocation方法:

geoFire.setLocation("location", new GeoLocation(37.7853889, -122.4056973), new GeoFire.CompletionListener() {
    @Override
    public void onComplete(String key, FirebaseError error) {
        if (error != null) {
            System.err.println("There was an error saving the location to GeoFire: " + error);
        } else {
            System.out.println("Location saved on server successfully!");
        }
    }
});

设置位置后,您可以检索它并将值保存到数据库:

geoFire.getLocation("location", new LocationCallback() {
    @Override
    public void onLocationResult(String key, GeoLocation location) {
        if (location != null) {
            System.out.println(String.format("The location for key %s is [%f,%f]", key, location.latitude, location.longitude))
// save longitude and latitude to db
            Double longi = location.longitude;
            Double lat = location.latitude
        } else {
            System.out.println(String.format("There is no location for key %s in GeoFire", key));
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        System.err.println("There was an error getting the GeoFire location: " + databaseError);
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.