Android应用程序地图的当前位置lat,并长时间发送到firebase吗()

博观而约取,厚积而薄发。这篇文章主要讲述Android应用程序地图的当前位置lat,并长时间发送到firebase吗?相关的知识,希望能为你提供帮助。
我的地图会自动找到当前位置,但不会发送到Firebase。如果在地图中添加标记,它将纬度和经度发送到火力场。但是我需要将当前位置lat和long尽快发送到我的Firebase数据库,因为它会找到我的位置。根据代码,因为我认为将添加标记的数据库部分替换为地理编码区域将把纬度和冗长的字符发送到Firebase,但我不知道如何正确执行。谁能帮我修复代码?谢谢
这是代码

package com.example.policeemergencysystem; import androidx.annotation.RequiresApi; import androidx.fragment.app.FragmentActivity; import android.os.Build; import android.os.Bundle; import com.example.policeemergencysystem.Prevelant.Prevelant; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.content.IntentSender; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.policeemergencysystem.Model.AdminOrders; import androidx.annotation.NonNull; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.ResolvableApiException; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResponse; import com.google.android.gms.location.LocationSettingsStates; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.example.policeemergencysystem.Prevelant.Prevelant; import com.google.firebase.database.ValueEventListener; import java.io.IOException; import java.util.HashMap; import java.util.List; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback{private GoogleMap mMap; private Button doneBtn; TextView backBtn; Marker myMarker; LocationManager locationManager; private static final String TAG = "MainActivity"; private String name; private String userID = "", userNAME = "", userPHONE = ""; DatabaseReference ordersRef = FirebaseDatabase.getInstance().getReference() .child("Location") .child(Prevelant.currentOnlineUser.getUsername()); @RequiresApi(api = Build.VERSION_CODES.M) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); doneBtn = (Button) findViewById(R.id.doneBtn); backBtn = (TextView) findViewById(R.id.backBtn); userID = getIntent().getStringExtra("uid"); userNAME = getIntent().getStringExtra("uname"); userPHONE = getIntent().getStringExtra("uphone"); backBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MapsActivity.this, HomeActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); startActivity(intent); } }); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); LocationRequest mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(10); mLocationRequest.setSmallestDisplacement(10); mLocationRequest.setFastestInterval(10); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); builder.addLocationRequest(mLocationRequest); Task< LocationSettingsResponse> task= LocationServices.getSettingsClient(this).checkLocationSettings(builder.build()); task.addOnCompleteListener(new OnCompleteListener< LocationSettingsResponse> () { @Override public void onComplete(Task< LocationSettingsResponse> task) { try { LocationSettingsResponse response = task.getResult(ApiException.class); // All location settings are satisfied. The client can initialize location // requests here.} catch (ApiException exception) { switch (exception.getStatusCode()) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the // user a dialog. try { // Cast to a resolvable exception. ResolvableApiException resolvable = (ResolvableApiException) exception; // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). resolvable.startResolutionForResult( MapsActivity.this, 101); } catch (IntentSender.SendIntentException e) { // Ignore the error. } catch (ClassCastException e) { // Ignore, should be an impossible error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. break; } } } }); locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED & & checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; }//Check whether the network provider is enabled if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() { @Override public void onLocationChanged(Location location) { //Get the Latitude double latitude = location.getLatitude(); //Get the Longitude double longitude = location.getLongitude(); //Instantiate the class, LatLng LatLng latLng = new LatLng(latitude, longitude); //Instantiate the class, GeoCoder Geocoder geocoder = new Geocoder(getApplicationContext()); try { List< Address> addressList = geocoder.getFromLocation(latitude, longitude, 1); String str = addressList.get(0).getLocality()+","; str += addressList.get(0).getCountryName()+","; str += addressList.get(0).getPostalCode(); mMap.addMarker(new MarkerOptions().position(latLng).title(str)); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.0f)); } catch (IOException e) { e.printStackTrace(); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} @Override public void onProviderDisabled(String provider) {} }); } else if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() { @Override public void onLocationChanged(Location location) { //Get the Latitude double latitude = location.getLatitude(); //Get the Longitude double longitude = location.getLongitude(); //Instantiate the class, LatLng LatLng latLng = new LatLng(latitude, longitude); String name = new String(Prevelant.currentOnlineUser.getUsername()); //Instantiate the class, GeoCoder Geocoder geocoder = new Geocoder(getApplicationContext()); try { List< Address> addressList = geocoder.getFromLocation(latitude, longitude, 1); String str = addressList.get(0).getLocality()+","; str += addressList.get(0).getCountryName()+","; str += addressList.get(0).getPostalCode(); mMap.addMarker(new MarkerOptions().position(latLng).title(str)); CameraPosition cameraPosition = new CameraPosition.Builder() .target(latLng) .zoom(17).build(); //Zoom in and animate the camera. mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } catch (IOException e) { e.printStackTrace(); } } @Override public void onStatusChanged(String provider, int status, Bundle extras) {} @Override public void onProviderEnabled(String provider) {} @Override public void onProviderDisabled(String provider) {} }); } }@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { final LocationSettingsStates states = LocationSettingsStates.fromIntent(data); switch (requestCode) { case 101: switch (resultCode) { case Activity.RESULT_OK: // All required changes were successfully made Toast.makeText(MapsActivity.this,states.isLocationPresent()+"",Toast.LENGTH_SHORT).show(); break; case Activity.RESULT_CANCELED: // The user was asked to change settings, but chose not to Toast.makeText(MapsActivity.this,"Canceled",Toast.LENGTH_SHORT).show(); break; default: break; } break; } }@Override public void onMapReady(final GoogleMap googleMap) { mMap = googleMap; Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show(); mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() { @Override public void onMapLongClick(LatLng latLng) {// First check if myMarker is null if (myMarker == null) {// Marker was not set yet. Add marker: myMarker = googleMap.addMarker(new MarkerOptions() .position(latLng) .title("Home Location") .snippet("Put the marker to your home location")); doneBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {Toast.makeText(MapsActivity.this, "Your location has been placed!", Toast.LENGTH_SHORT).show(); HashMap< String, Object> userMap = new HashMap< > (); DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Orders").child(Prevelant.currentOnlineUser.getUsername()); myRef.child("name").setValue(userNAME); myRef.child("phone").setValue(userPHONE); myRef.child(Prevelant.currentOnlineUser.getUsername()).updateChildren(userMap); //finish(); //Intent intent = new Intent(MapsActivity.this, HomeActivity.class); //startActivity(intent); } }); } else { // Marker already exists, just update it's position myMarker.setPosition(latLng); LatLng myLatLng = new LatLng(myMarker.getPosition().latitude, myMarker.getPosition().longitude); } HashMap< String, Object> adminMap = new HashMap< > (); DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("Orders").child(Prevelant.currentOnlineUser.getUsername()); LatLng myLatLng = new LatLng(myMarker.getPosition().latitude, myMarker.getPosition().longitude); myRef.child("latitude").setValue(myLatLng.latitude); myRef.child("longitude").setValue(myLatLng.longitude); myRef.child(Prevelant.currentOnlineUser.getUsername()).updateChildren(adminMap); } }); } }

答案【Android应用程序地图的当前位置lat,并长时间发送到firebase吗()】在您的oncreate函数中,获取当前位置,并在将标记的位置保存到数据库中时,可以获取当前位置的经纬度并保存。每次您打开此活动,它都会获取当前位置并保存。

    推荐阅读