Detect if device has taken a turn using location service android

邮差的信 提交于 2019-12-10 11:54:35

问题


I want to detect if the user has taken a turn on the road while driving using the sensors on the android phone. How do I code this? I am collecting data live from all the sensors(accelerometer,location,rotation,geomagnetic) and storing them on the sd card. So now i just want to know whether the user has a taken a turn and in which direction he has turned.


回答1:


I assume the registration of the sensor is done properly. You can detect the direction by using the orientation sensor (deprecated) as follows:

@Override
public void onSensorChanged(SensorEvent event) {

    float azimuth_angle = event.values[0];
    int precision = 2;

    if (prevAzimuth - azimuth_angle < precision * -1)
        Log.v("->", "RIGHT");

    else if (prevAzimuth - azimuth_angle > precision)
        Log.v("<-", "LEFT");

    prevAzimuth = azimuth_angle;

}

Note: The variable of "prevAzimuth" is declared as global. You can change "precision" value to whatever you want. We need this value because we do not want to see output after each trivial change in azimuth angle. However, too large precision gives imprecise results. To me, "2" is optimum.




回答2:


If you are tracking location coordinates, you can also track shifts between the angle from previous locations.

angle = arctan((Y2 - Y1) / (X2 - X1)) * 180 / PI

See this answer for calculating x and y.

Decision to use sensor values is based on an unrealistic assumption that the device is never rotated with respect to the vehicle.



来源:https://stackoverflow.com/questions/30557545/detect-if-device-has-taken-a-turn-using-location-service-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!