Tengo 2 puntos (objetos de ubicación de Android): ubicación actual y ubicación de destino. También tengo una dirección (en grados) de mi dispositivo.
Quiero calcular un ángulo entre la ubicación y la dirección del objetivo. ¿Cómo hacerlo correctamente?
Recibo la ubicación de FusedLocationProvider (si es importante). Ahora solo uso
float requiredAngle = Math.abs(location.getBearing() - 180 - target.bearingTo(location));
float angleBetween = Math.abs(requiredAngle - location.getBearing()); y devuelve un ángulo incorrecto.
Creo que debería calcular la diferencia entre el norte verdadero y el norte magnético y agregar la dirección del dispositivo. Luego use currentPosition.bearingTo(target) y reste la dirección del dispositivo del rumbo.
En ese caso, puede consultar este artículo: https://onlinemschool.com/math/library/vector/angl/
Fórmula para el ángulo entre el vector A y el vector B: coseno (alfa) = puntoProductAB / (magnitudA * magnitudB)
Este ángulo se llama rumbo relativo .
Registre oyentes en Sensor.TYPE_ROTATION_VECTOR, Sensor.TYPE_ACCELEROMETER, Sensor.TYPE_MAGNETIC_FIELD. Me gusta:
sensorManager.registerListener(listener, sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), SensorManager.SENSOR_DELAY_NORMAL);Entonces haz un oyente para esto:
private float[] gravity; private float[] geomagnetic; private float[] R = new float[9]; private float[] I = new float[9]; @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { gravity = sensor.values(); // Just save the values } if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { geomagnetic = sensor.values(); } if (SensorManager.getRotationMatrix(R, I, gravity, geomagnetic)) { // If something is wrong (like device is in free fall) float orientation[] = new float[3]; SensorManager.getOrientation(R, orientation); // Now you have values from -PI to PI float heading; if (R[0] > 0) { // R[0] is heading heading = R[0] * 180 / PI; } else { // -PI, eq. from South to West to North heading = (Math.abs(R[0]) * 180 / PI) * 2; } float relativeBearing = location.bearingTo(target) - heading; if (relativeBearing < 0) { relativeBearing = 360 + relativeBearing; } } }Documentación: https://developer.android.com/reference/android/hardware/SensorManager#getRotationMatrix(float[],%20float[],%20float[],%20float[]) https://developer.android.com /referencia/android/hardware/SensorManager#getOrientation(float[],%20float[])