android 计算准确的 gps 距离。之间的距离

标签 android gps distance

我想计算用户在使用 GPS 的 Activity (例如运行)中走了多远的距离。即使GPS不准确,我也想要一个可以计算准确距离的功能。

在我下面的代码中,当我注释掉我的 onLocationChanged 代码时,我的应用程序没有崩溃。但是TextView和Toast这两个没有显示当前位置。 当我包含我的 onLocationChanged 代码时,我手机上的应用程序会在一段时间后崩溃。我无法弄清楚错误。

有人能告诉我我使用 Location.distanceBetween 的方式是否正确吗?我觉得有些不对劲,但不知道是什么。

更新的 Java 代码

public class MainActivity extends Activity{
    protected LocationManager locationManager;
    EditText userNumberInput;
    EditText userTextInput;
    TextView distanceText;
    TextView latitude;
    TextView longitude;
    double lat1,lon1,lat2,lon2,lat3,lon3,lat4,lon4;
    long dist;
    float[] result;
    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        distanceText=(TextView)findViewById(R.id.Distance);
        latitude=(TextView)findViewById(R.id.currentLat);
        longitude=(TextView)findViewById(R.id.currentLon);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationListener); 
        Log.d("GPS Enabled", "GPS Enabled");  
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = locationManager.getBestProvider(criteria, true);
        Location location=locationManager.getLastKnownLocation(provider);

        //Display current location in Toast
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        Toast.makeText(MainActivity.this, message,
                Toast.LENGTH_LONG).show();

        //Display current location in textview  
        latitude.setText("Current Latitude: " + String.valueOf(location.getLatitude())); 
        longitude.setText("Current Longitude: " + String.valueOf(location.getLongitude()));
        lat1 = location.getLatitude();
        lon1 = location.getLongitude();
        lat3 = 123.0;
        lon3 = 234.0;
        lat4 = 123.0;
        lon4 = 224.0;
        float[] results = new float[1]; 
        Location.distanceBetween(lat3, lon3, lat4, lon4, results);
        System.out.println("Distance is: " + results[0]);
    }

    private CharSequence ToString(double latitude2) {
        // TODO Auto-generated method stub
        return null;
    }

    LocationListener myLocationListener = new LocationListener() 
    {
        public void onLocationChanged(Location loc2) 
        {

        }
    }

    public void onProviderDisabled(String provider)
    {
        Toast.makeText(MainActivity.this,
                "GPS is disabled",
                Toast.LENGTH_LONG).show();
    }
    public void onProviderEnabled(String provider)
    {
        Toast.makeText(MainActivity.this,
                "GPS is enabled",
                Toast.LENGTH_LONG).show();
    }
    public void onStatusChanged(String provider, int status,
            Bundle extras)
    {
        Toast.makeText(MainActivity.this,
                "GPS status changed",
                Toast.LENGTH_LONG).show();
    }

    };

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(myLocationListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MINIMUM_TIME_BETWEEN_UPDATES,MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, myLocationListener);

    }
}

LogCat

01-29 15:37:24.070: I/Process(20836): Sending signal. PID: 20836 SIG: 9
01-29 15:37:38.305: D/GPS Enabled(24434): GPS Enabled
01-29 15:37:38.305: D/AndroidRuntime(24434): Shutting down VM
01-29 15:37:38.305: W/dalvikvm(24434): threadid=1: thread exiting with uncaught exception (group=0x40fe32a0)
01-29 15:37:38.305: E/AndroidRuntime(24434): FATAL EXCEPTION: main
01-29 15:37:38.305: E/AndroidRuntime(24434): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.validationapp/com.example.validationapp.MainActivity}: java.lang.NullPointerException
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.os.Looper.loop(Looper.java:137)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.main(ActivityThread.java:4898)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at java.lang.reflect.Method.invoke(Method.java:511)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at dalvik.system.NativeStart.main(Native Method)
01-29 15:37:38.305: E/AndroidRuntime(24434): Caused by: java.lang.NullPointerException
01-29 15:37:38.305: E/AndroidRuntime(24434):    at com.example.validationapp.MainActivity.onCreate(MainActivity.java:57)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.Activity.performCreate(Activity.java:5206)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
01-29 15:37:38.305: E/AndroidRuntime(24434):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
01-29 15:37:38.305: E/AndroidRuntime(24434):    ... 11 more
01-29 15:38:51.680: D/GPS Enabled(28843): GPS Enabled
01-29 15:38:51.685: D/AndroidRuntime(28843): Shutting down VM
01-29 15:38:51.685: W/dalvikvm(28843): threadid=1: thread exiting with uncaught exception (group=0x40fe32a0)
01-29 15:38:51.685: E/AndroidRuntime(28843): FATAL EXCEPTION: main
01-29 15:38:51.685: E/AndroidRuntime(28843): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.validationapp/com.example.validationapp.MainActivity}: java.lang.NullPointerException
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.access$600(ActivityThread.java:140)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.os.Looper.loop(Looper.java:137)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.main(ActivityThread.java:4898)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at java.lang.reflect.Method.invoke(Method.java:511)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at dalvik.system.NativeStart.main(Native Method)
01-29 15:38:51.685: E/AndroidRuntime(28843): Caused by: java.lang.NullPointerException
01-29 15:38:51.685: E/AndroidRuntime(28843):    at com.example.validationapp.MainActivity.onCreate(MainActivity.java:57)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.Activity.performCreate(Activity.java:5206)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
01-29 15:38:51.685: E/AndroidRuntime(28843):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
01-29 15:38:51.685: E/AndroidRuntime(28843):    ... 11 more

我再次运行,但它没有崩溃或显示任何输出。日志猫是

01-29 16:22:12.795: D/GPS Enabled(28011): GPS Enabled
01-29 16:22:12.800: I/System.out(28011): Distance is: 607178.94
01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.820: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.915: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.915: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.920: D/SensorManager(28011): registerListener :: handle = 0  name= LSM330DLC 3-axis Accelerometer delay= 200000 Listener= android.view.OrientationEventListener$SensorEventListenerImpl@41c3a408
01-29 16:22:12.960: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:22:12.960: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0

每当我在我的 EditText 上输入一个字母时,logcat 就会不断增加

01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[1] is 67
01-29 16:23:42.500: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[2] is 67
01-29 16:23:42.505: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:23:42.505: E/Dynamiclayout(28011): java.lang.IndexOutOfBoundsException: charAt: 0 >= length 0
01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[0] is 64
01-29 16:23:42.520: D/TextLayoutCache(28011): TextLayoutCache::replaceThai, prevBuffer[1] is 67

这种类型的代码。我输入的每个字母越多,所以我无法将其全部粘贴到这里

最佳答案

你可以像这样设置你的Location Manager

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
Log.d("GPS Enabled", "GPS Enabled"); 
provider = locationManager.getBestProvider(criteria, true);    
criteria.setAccuracy(Criteria.ACCURACY_FINE);

现在,您可以像这样显示LatitudeLongitude:

 latitude.setText(String.valueOf(location.getLatitude()));
 longitude.setText(String.valueOf(location.getLongitude())); 

现在,找到两点之间的距离,如下所示:

float[] results = new float[1];
Location.distanceBetween(
                des_pos.latitude,des_pos.longitude,
                cur_pos.latitude, cur_pos.longitude, results);

            System.out.println("Distance is: " + results[0]);

试试这个

更新: 转到此 More about Location.distanceBetween(..)

更新2:

您只想删除对您的Activity Pause() 的更新:

    @Override
protected void onPause() {
    super.onPause();
    locationManager.removeUpdates(this);
}

并且,还要继续您的 Activity Resume():

@Override
protected void onResume() {
    super.onResume();
     locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

}

关于android 计算准确的 gps 距离。之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21422234/

相关文章:

java - 更改具有相同屏幕尺寸的设备时的设计更改

android - 我如何计算使用 Task Killers 的用户?

android - 如何在android中使用GPS_PROVIDER获取当前准确的GPS坐标?

javascript - 使用 Meteor/Mongo 手动查找最近的坐标

sql - 计算一列中不同条目之间的距离

android - 值错误: Invalid tensors 'input' were found

android sdk获取广播自动续订订阅

iphone - 解码图像属性中的 GPS 坐标

LINQ POI 邻近度

matlab - Lat/Lng 点到 Minor Arc 段的距离