从Firebase中检索已保存的LatLong值并显示在标记中 [英] Retrieve saved LatLong value from Firebase and show in marker

查看:176
本文介绍了从Firebase中检索已保存的LatLong值并显示在标记中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前曾经问过类似的问题,在Firebase云中保存数据的问题。我设法保存了纬度& firebase数据库中的经度数据,使用下面的代码:

$ @ $ $ $ b $ public void onMapReady { b mMap = map;
//使用自定义信息窗口适配器来处理
// info窗口内容中的多行文本。

mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter(){

@Override
//在这里返回null,这样就调用getInfoContents()。 $ b public View getInfoWindow(Marker arg0){
return null;
}

@Override
public View getInfoContents(Marker marker){
//膨胀信息窗口,标题和片段的布局。
查看infoWindow = getLayoutInflater()。inflate(R.layout.custom_info_contents,
(FrameLayout)findViewById(R.id.map),false);

TextView title =((TextView)infoWindow.findViewById(R.id.title));
title.setText(marker.getTitle());

TextView snippet =((TextView)infoWindow.findViewById(R.id.snippet));
snippet.setText(marker.getSnippet());

return infoWindow;
}
});

//打开我的位置图层和地图上的相关控件。
updateLocationUI();

//获取设备的当前位置并设置地图的位置。
getDeviceLocation();
}

//获取设备的当前位置,并定位地图的相机。

private void getDeviceLocation(){
/ *
*请求位置权限,以便我们可以获取
*设备的位置。权限请求的结果由回调
* onRequestPermissionsResult处理。
* /
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
mLocationPermissionGranted = true;
} else {
ActivityCompat.requestPermissions(this,
new String [] {android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}

FirebaseDatabase数据库= FirebaseDatabase.getInstance();
DatabaseReference databaseReference = database.getReference();

Intent intent = getIntent();
callingActivity = intent.getIntExtra(callingActivity,0);
//如果已经从ScanActivity
调用映射if(callingActivity == 1){

//获取设备的最佳位置和最近位置
if(mLocationPermissionGranted){
mLastKnownLocation = LocationServices.FusedLocationApi
.getLastLocation(mGoogleApiClient);

scanString = intent.getStringArrayListExtra(beaconList);
nameList = intent.getStringArrayListExtra(nameList);
addressList = intent.getStringArrayListExtra(addressList);
RssiList = intent.getIntegerArrayListExtra(RssiList); (int i = 0; i< scanString.size(); i ++){
addBeacon.name = nameList.get(i);


addBeacon.address = addressList.get(i);
addBeacon.Rssi = RssiList.get(i);
addBeacon.latitude = mLastKnownLocation.getLatitude();
addBeacon.longitude = mLastKnownLocation.getLongitude();
databaseReference.child(foo).child(addBeacon.address).setValue(addBeacon);



$ / code $ / pre

但问题是当我尝试检索我看到的位置是我的设备的位置,而不是Firebase数据库中保存的latlong值。我有2个调用活动,即1是用于存储长的火力基地和2检索它。我可以成功地将值保存在唯一的ID并更新它,而我无法检索latlong。我正在使用以下代码进行检索:

  else {


DatabaseReference latlong = FirebaseDatabase。 getInstance()。getReference()。child(foo).child(08:9E:08:B4:57:18);
mFirebaseDatabase.keepSynced(true);

ValueEventListener beaconListener = new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
LatLng newLocation = new LatLng(
dataSnapshot .child(latitude)。getValue(Long.class),
dataSnapshot.child(longitude)。getValue(Long.class));
// LatLng mRetrieved = new LatLng(dataSnapshot.getValue(beacon.class).latitude,dataSnapshot.getValue(beacon.class).longitude);
//mLastKnownLocation.setLatitude(dataSnapshot.getValue(beacon.class).latitude);
// mLastKnownLocation.setLatitude(60.192059);
mMap.addMarker(new MarkerOptions()
.position(newLocation)
.title(dataSnapshot.getKey()));
}

@Override
public void onCancelled(DatabaseError databaseError){


};
databaseReference.addValueEventListener(beaconListener);

在这里,我正在改变1个特定子名08:9E:08:B4 :57:18在数据库中手动检查,如果我可以在地图上看到标记,但它只显示我的设备的当前位置。

如果需要,我可以在应用程序中提供更多的数据库屏幕截图。提前致谢。希望有一些有价值的指针。

解决方案

请在添加标记后添加此代码,以便标记将移动到您添加的位置。 b
$ b

  try {
CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(lat,lng));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
googleMap.moveCamera(center);
googleMap.animateCamera(zoom);
} catch(Exception e){
Log.getStackTraceString(e);
}


I have previously asked the similar question where I had issue with saving the data in the firebase cloud. I managed to store the latitude & longitude data in the firebase database using following code

 @Override
public void onMapReady(GoogleMap map) {
    mMap = map;
    // Use a custom info window adapter to handle multiple lines of text in the
    // info window contents.

    mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

        @Override
        // Return null here, so that getInfoContents() is called next.
        public View getInfoWindow(Marker arg0) {
            return null;
        }

        @Override
        public View getInfoContents(Marker marker) {
            // Inflate the layouts for the info window, title and snippet.
            View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
                    (FrameLayout)findViewById(R.id.map), false);

            TextView title = ((TextView) infoWindow.findViewById(R.id.title));
            title.setText(marker.getTitle());

            TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
            snippet.setText(marker.getSnippet());

            return infoWindow;
        }
    });

    // Turn on the My Location layer and the related control on the map.
    updateLocationUI();

    // Get the current location of the device and set the position of the map.
    getDeviceLocation();
}

 // Gets the current location of the device, and positions the map's camera.

private void getDeviceLocation() {
    /*
     * Request location permission, so that we can get the location of the
     * device. The result of the permission request is handled by a callback,
     * onRequestPermissionsResult.
     */
    if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
            android.Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        mLocationPermissionGranted = true;
    } else {
        ActivityCompat.requestPermissions(this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
    }

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference databaseReference = database.getReference();

    Intent intent = getIntent();
    callingActivity = intent.getIntExtra(  "callingActivity",0 );
    //If the map has been called from ScanActivity
    if (callingActivity == 1) {

        // Get the best and most recent location of the device
        if (mLocationPermissionGranted) {
            mLastKnownLocation = LocationServices.FusedLocationApi
                    .getLastLocation( mGoogleApiClient );

            scanString = intent.getStringArrayListExtra( "beaconList" );
            nameList = intent.getStringArrayListExtra( "nameList" );
            addressList = intent.getStringArrayListExtra( "addressList" );
            RssiList = intent.getIntegerArrayListExtra( "RssiList" );

            for ( int i=0; i < scanString.size(); i++) {
                addBeacon.name = nameList.get( i );
                addBeacon.address = addressList.get( i );
                addBeacon.Rssi = RssiList.get( i );
                addBeacon.latitude = mLastKnownLocation.getLatitude();
                addBeacon.longitude = mLastKnownLocation.getLongitude();
                databaseReference.child( "foo" ).child(addBeacon.address).setValue( addBeacon);
            }
        }
    }

But the problem is when I try to retrieve the location I see is my device's location instead of the saved latlong value in the firebase data base. I have 2 calling activities i.e. 1 is for storing the lat long to firebase and 2 for retrieving it. I can successfully save the value under unique id and update it whereas I am unable to retrieve the latlong. I am using following code for retrieval

        else {


     DatabaseReference latlong= FirebaseDatabase.getInstance().getReference().child( "foo" ).child( "08:9E:08:B4:57:18" );
      mFirebaseDatabase.keepSynced(true);

         al ValueEventListener beaconListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                LatLng newLocation = new LatLng(
                        dataSnapshot.child("latitude").getValue(Long.class),
                        dataSnapshot.child("longitude").getValue(Long.class));
                //LatLng mRetrieved = new LatLng(dataSnapshot.getValue(beacon.class).latitude, dataSnapshot.getValue(beacon.class).longitude);
                //mLastKnownLocation.setLatitude( dataSnapshot.getValue(beacon.class).latitude );
                // mLastKnownLocation.setLatitude(60.192059);
                mMap.addMarker( new MarkerOptions()
                        .position( newLocation)
                        .title( dataSnapshot.getKey()));
        }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        databaseReference.addValueEventListener( beaconListener );

Here i am changing the lat long value of 1 particular child name "08:9E:08:B4:57:18" manually in database to check if i can see the marker in the map at that location but it just shows my device's current location.

I can provide further screen shot of my database n the application if required. Thanks in advance. Hope to have some valuable pointers.

解决方案

Please add this code after adding marker, so that the marker will move to the location which you added

try {
            CameraUpdate center = CameraUpdateFactory.newLatLng(new LatLng(lat, lng));
            CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
            googleMap.moveCamera(center);
            googleMap.animateCamera(zoom);
        } catch (Exception e) {
            Log.getStackTraceString(e);
        } 

这篇关于从Firebase中检索已保存的LatLong值并显示在标记中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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