距离总是等于零

时间:2014-04-08 23:26:47

标签: android gps distance

我有一个用gps计算距离和速度的应用程序 速度很快 但距离总是等于零!!

起初我没有将float [] dist初始化为零..但是一旦找到gps就崩溃了!

这就是代码

public class Main_Activity extends Activity {

    TextView tvdistance;
    TextView tvSpeed;

    double currentLon = 0;
    double currentLat = 0;
    double lastLon = 0;
    double lastLat = 0;
    double distance = 0;
    float[] dist = {
            0, 0, 0
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);
        tvdistance = (TextView) findViewById(R.id.tvdistance);
        tvSpeed = (TextView) findViewById(R.id.tvspeed1);

        LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);
        Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (loc == null) {
            tvdistance.setText("No GPS location found");
        }
        else {
            // set Current latitude and longitude
            currentLon = loc.getLongitude();
            currentLat = loc.getLatitude();

        }
        // Set the last latitude and longitude
        lastLat = currentLat;
        lastLon = currentLon;

    }

    LocationListener Loclist = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub

            // start location manager
            LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Get last location
            Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            // Request new location
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, Loclist);

            // Get new location
            Location loc2 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            // get the current lat and long
            currentLat = loc.getLatitude();
            currentLon = loc.getLongitude();

            if (currentLat != 0 && currentLon != 0) {

                Location.distanceBetween(currentLat, currentLon, location.getLatitude(),
                        location.getLongitude(), dist);
                distance += (long) dist[0];
            }

            currentLat = location.getLatitude();
            currentLon = location.getLongitude();

            float speed = location.getSpeed();
            tvSpeed.setText("Speed = " + speed / 1000 * 60 * 60 + "Km/h");
            tvdistance.setText("Distance = " + distance);

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

    };

}

2 个答案:

答案 0 :(得分:0)

由于您刚刚获得了位置修复,我完全希望从getLastKnownLocation返回的位置与您在location中获得的位置相同。这意味着两者之间的距离正确0。如果您想要旧位置,则需要自己存储。

答案 1 :(得分:-1)

以下是从GPS提供商处获取位置更新的完整代码

public class MainActivity extends Activity {

private GoogleMap googleMap;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 1
                                                                // meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1
                                                        // second
// Declaring a Location Manager
protected LocationManager locationManager;

// The alert dialog to enable GPS
private Dialog alertDialog;

// flag for GPS status
boolean isGPSEnabled = false;

Location location; // location

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

/*
 * (non-Javadoc)
 * 
 * @see android.app.Activity#onStart()
 */
@Override
protected void onStart() {
    // fetching your current location
    super.onStart();

    googleMap = ((MapFragment) getFragmentManager().findFragmentById(
            R.id.map)).getMap();

    if (googleMap != null) {

        googleMap.setMyLocationEnabled(true);
        googleMap.getUiSettings().setZoomControlsEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        googleMap.getUiSettings().setAllGesturesEnabled(true);

    }

    // Getting current location and adding the marker

    locateMe();

}

/**
 * 
 */
private void locateMe() {
    // Checking for GPS Enabled

    locationManager = (LocationManager) this
            .getSystemService(Context.LOCATION_SERVICE);

    // getting GPS status
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (!isGPSEnabled) {
        // GPS is disabled

        askUserToEnableGPS();

    }

}

/**
 * 
 */
private void askUserToEnableGPS() {
    // Asking user to enable GPS

    // 1. Instantiate an AlertDialog.Builder with its constructor
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    // 2. Chain together various setter methods to set the dialog
    // characteristics
    builder.setMessage(R.string.generic_gps_not_found)
            .setTitle(R.string.generic_gps_not_found_message_title)
            .setPositiveButton(R.string.generic_yes,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            // User selected yes
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    })
            .setNegativeButton(R.string.generic_no,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            // User selected no
                        }
                    });

    // 3. Get the AlertDialog from create()
    AlertDialog dialog = builder.create();
    dialog.show();

}

/*
 * (non-Javadoc)
 * 
 * @see android.app.Activity#onResume()
 */
@Override
protected void onResume() {
    // Getting location from GPS
    super.onResume();

    // getting GPS status
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    if (isGPSEnabled) {

        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,
                MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
        Log.e("GPS Enabled", "GPS Enabled");

        location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    }

}

LocationListener listener = new LocationListener() {

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLocationChanged(Location arg0) {
        // Setting the marker

        if (googleMap == null || location == null) {
            return;
        } else {

            googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
                    location.getLatitude(), location.getLongitude())));

            final Handler handler1 = new Handler();
            handler1.postDelayed(new Runnable() {
                @Override
                public void run() {
                    // Do something after 3000ms
                    googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));

                }
            }, 1000);

            Marker myLocation = googleMap.addMarker(new MarkerOptions()
                    .position(
                            new LatLng(location.getLatitude(), location
                                    .getLongitude()))
                    .title("Me")
                    .snippet("I am here")
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.drawable.ic_launcher)));

        }

        locationManager.removeUpdates(listener);
        locationManager = null;

    }
};

}

现在您可以使用各种方法来存储您的位置。以下是一些方法:

  1. 共享偏好
  2. SQLite数据库
  3. Web服务器
  4. 保存在文件中
  5. 您可以参考this链接。