gpt4 book ai didi

android - Location.distanceBetween 获取不到距离、范围、米,无法识别latlong变量

转载 作者:行者123 更新时间:2023-11-30 01:40:16 25 4
gpt4 key购买 nike

如果他让圆圈,我试图从用户那里获取范围,但我无法在屏幕上获取范围或距离,它始终显示 0.0,并且不显示 toast 。

public class HomeActivity extends AppCompatActivity implements OnMapReadyCallback {
/**
* Request code for location permission request.
*
* @see #onRequestPermissionsResult(int, String[], int[])
*/
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

/**
* Flag indicating whether a requested permission has been denied after
returning in
* {@link #onRequestPermissionsResult(int, String[], int[])}.
*/
private boolean mPermissionDenied = false;

LatLng latLng;
GoogleMap mMap;
SupportMapFragment supportMapFragment;
Marker marker;

//textview para mostrar el email, nombre, id del usuario conectado actualmente
TextView textViewEmail;

Context context;

double latitudeF, longitudeF;

TextView locationText;
TextView tiempoText;
TextView rangoText;
TextView longitudeText;
TextView latitudeText;

//Float distance;

Circle circle;

String dist;

private static final String TAG = "MyApp";

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

supportMapFragment = (SupportMapFragment) getSupportFragmentManager
().findFragmentById(R.id.mapHomeUbication);
supportMapFragment.getMapAsync(this);

context = this;

// inicializamos el textview
textViewEmail = (TextView)findViewById(R.id.txt_EmailUsuario);
locationText = (TextView) findViewById(R.id.location);
longitudeText = (TextView) findViewById(R.id.longitude);
latitudeText = (TextView) findViewById(R.id.latitude);
tiempoText = (TextView) findViewById(R.id.tiempo);
rangoText = (TextView )findViewById(R.id.rango);

// cargamos el email desde sharedpreferences
SharedPreferences sharedPreferences = getSharedPreferences
(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "No Disponible");

// mostramos el email actualmente logueado
textViewEmail.setText("Usuario : " + email);

onMapReady(mMap);

}

// function salir
private void logout() {
//Creating an alert dialog to confirm logout
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Esta seguro que quiere salir?");
alertDialogBuilder.setPositiveButton("Sí",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {

//Getting out sharedpreferences
SharedPreferences preferences = getSharedPreferences
(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);
//Getting editor
SharedPreferences.Editor editor = preferences.edit();

//Puting the value false for loggedin
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);

//Putting blank value to email
editor.putString(Config.EMAIL_SHARED_PREF, "");

//Saving the sharedpreferences
editor.commit();

//Starting login activity
Intent intent = new Intent(HomeActivity.this,
LoginActivity.class);
startActivity(intent);
}
});

alertDialogBuilder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {

}
});

//Showing the alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
//Adding our menu to toolbar
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.log_OutMenu) {
//calling logout method when the logout button is clicked
logout();
}
return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {

super.onBackPressed();
finish();

}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

setUpMap();
}

/**
* This is where we can add markers or lines, add listeners or move the camera.
In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once.
*/
private void setUpMap() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this,
LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(myLocationChangeListener());
}
}

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
return new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
LatLng latLngI = new LatLng(location.getLatitude(),
location.getLongitude());
longitudeF = location.getLongitude();
latitudeF = location.getLatitude();

DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date(location.getTime());
String formatted = format.format(date);
tiempoText.setText(formatted.toString());

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng
(latitudeF, longitudeF), 13));

MarkerOptions options = new MarkerOptions();

// Setting the position of the marker

options.position(new LatLng(latitudeF, longitudeF));

latLng = new LatLng(latitudeF, longitudeF);

drawMarkerWithCircle(latLng);

// Get back the mutable Circle
//circle = mMap.addCircle(circleOptions);

//getDistance(latLngI, latLng);

float[] distance = new float[2];

Location.distanceBetween( marker.getPosition().latitude,
marker.getPosition().longitude,
circle.getCenter().latitude, circle.getCenter
().longitude, distance);

if (distance[0] > circle.getRadius()) {
Toast.makeText(getBaseContext(), "fuera del rango: "
+ distance[0] + " radio: " + circle.getRadius(), Toast.LENGTH_LONG).show();
} else if (distance[0] < circle.getRadius()) {
Toast.makeText(getBaseContext(), "dentro del rango: "
+ distance[0] + " radio: " + circle.getRadius() , Toast.LENGTH_LONG).show();
}

//mMap.addMarker(new MarkerOptions().position(latLng));
//mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,8.0f));
locationText.setText("estas en [" + longitudeF + " ; " + latitudeF
+ "] ");
Log.d(TAG, "onMyLocationChange: 1" + distance);
}
};
}

private void drawMarkerWithCircle(LatLng position) {
double radiusInMeters = 300;
int strokeColor = 0xffff0000; //red outline
int shadeColor = 0x44ff0000; //opaque red fill

CircleOptions circleOptions = new CircleOptions().center(position).radius
(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
circle = mMap.addCircle(circleOptions);

MarkerOptions markerOptions = new MarkerOptions().position(position);
marker = mMap.addMarker(markerOptions);
}
}

这是 logcat,它只显示一个数组,但如果移动标记,它看起来总是在变化

01-04 04:03:31.766 5838-5864/com.google.android.gms.persistent I/dalvikvm: Could not find method android.location.Location.isFromMockProvider, referenced from method com.google.android.location.util.am.e 01-04 04:03:31.766 5838-5864/com.google.android.gms.persistent W/dalvikvm: VFY: unable to resolve virtual method 995: Landroid/location/Location;.isFromMockProvider ()Z 01-04 04:03:31.766 5838-5864/com.google.android.gms.persistent D/dalvikvm: VFY: replacing opcode 0x6e at 0x0019 01-04 04:03:31.822 9501-9501/com.jhon.co.divi D/MyApp: onMyLocationChange: 1[F@53a75360 01-04 04:03:31.834 5838-5838/com.google.android.gms.persistent I/dalvikvm: Could not find method android.os.Looper.quitSafely, referenced from method com.google.android.gms.fitness.service.b.c.onDestroy 01-04 04:03:31.842 5838-5838/com.google.android.gms.persistent W/dalvikvm: VFY: unable to resolve virtual method 1351: Landroid/os/Looper;.quitSafely ()V 01-04 04:03:31.842 5838-5838/com.google.android.gms.persistent D/dalvikvm: VFY: replacing opcode 0x6e at 0x000f 01-04 04:03:31.854 5838-5838/com.google.android.gms.persistent V/GeofencerHelper: Initializing geofence's system cache. 01-04 04:03:31.862 5838-5858/com.google.android.gms.persistent D/GeofenceStateCache: Recovered 0 geofences. 01-04 04:03:31.886 5838-5838/com.google.android.gms.persistent I/dalvikvm: Could not find method android.os.Process.myUserHandle, referenced from method com.google.android.location.internal.server.o.f 01-04 04:03:31.886 5838-5838/com.google.android.gms.persistent W/dalvikvm: VFY: unable to resolve static method 1464: Landroid/os/Process;.myUserHandle ()Landroid/os/UserHandle; 01-04 04:03:31.886 5838-5838/com.google.android.gms.persistent D/dalvikvm: VFY: replacing opcode 0x71 at 0x00a7

它是这样的:

enter image description here

我不明白为什么它总是返回 0.0 并且不在 Location.distanceBetween 中进行验证。

最佳答案

            postRef.addChildEventListener( new ChildEventListener() {

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {

if (!dataSnapshot.exists()) {
// Toast.makeText(this, "if", Toast.LENGTH_SHORT ).show();

} else {

String latitude_Display = dataSnapshot
.child( "Pro_file" )
.child( "bpro_latitude" )
.getValue().toString();

String longitude_Display = dataSnapshot
.child( "Pro_file" )
.child( "bpro_longitude" )
.getValue().toString();

//Toast.makeText(this, "else " + latitude_Display + "\n" + longitude_Display, Toast.LENGTH_SHORT ).show();

String latLng = latitude_Display;
String latLng1 = longitude_Display;

double latitude_C = Double.parseDouble(latLng);
double longitude_C = Double.parseDouble(latLng1);

LocationManager locationManager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
Criteria crit = new Criteria();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation( locationManager.getBestProvider( crit, false ) );
float[] distance = new float[2];
CircleOptions circleOptions_b = new CircleOptions();
circleOptions_b.center(new LatLng(location.getLatitude(), location.getLongitude()));
circleOptions_b.radius(100000);
Location.distanceBetween( latitude_C, longitude_C,
circleOptions_b.getCenter().latitude, circleOptions_b.getCenter().longitude, distance);

if( distance[0] > circleOptions_b.getRadius() ){
Toast.makeText(this, "the user Outside", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "the user Inside", Toast.LENGTH_LONG).show();
//do something
listUsers.add( dataSnapshot
.child("Pro_file")
.getValue(user.class) );

displayUsers(listUsers);
find_myAdapter.notifyDataSetChanged();
}
}
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
find_myAdapter.notifyDataSetChanged();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(this,"Canceled",Toast.LENGTH_SHORT).show();
find_myAdapter.notifyDataSetChanged();
}
});


}

关于android - Location.distanceBetween 获取不到距离、范围、米,无法识别latlong变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com