java - Android - 使用 Haversine 公式计算距离(使用 GPS、Lat 和 Long)

标签 java android distance

我需要一些帮助:) 我被分配了一个项目来计算距离/速度和时间。我已经和定时器一起出来了。但是,距离给我带来了一些问题。从我从一个地方到另一个地方,距离根本没有改变。

//全局定位系统

private static Double EARTH_RADIUS = 6371.00; // Radius in Kilometers default

private static final String DEBUG_TAG = "GPS";
private String[] location;
private double[] coordinates;
private double[] gpsOrg;
private double[] gpsEnd;

private LocationManager lm;
private LocationListener locationListener;

private double totalDistanceTravel;
private boolean mPreviewRunning;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.waterspill);

    /*getWindow().setFormat(PixelFormat.TRANSLUCENT);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);*/

    mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
    mSurfaceHolder = mSurfaceView.getHolder();
    mSurfaceHolder.addCallback(this);
    mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);


   distanceCal=new LocationUtil(EARTH_RADIUS);
    totalDistanceTravel=0;

    // ---Additional---
    //mapView = (MapView) findViewById(R.id.mapview1);

    //mc = mapView.getController();
    // ----------------
    txtTimer = (TextView) findViewById(R.id.Timer);
    gpsOnOff = (TextView) findViewById(R.id.gpsOnOff);
    disTrav = (TextView) findViewById(R.id.disTrav);
    startButton = (Button) findViewById(R.id.startButton);
    startButton.setOnClickListener(startButtonClickListener);
    stopButton = (Button) findViewById(R.id.stopButton);
    stopButton.setOnClickListener(stopButtonClickListener);
    testButton = (Button) findViewById(R.id.testButton);
    testButton.setOnClickListener(testButtonClickListener);

    startButton.setEnabled(false);
    stopButton.setEnabled(false);

    getLocation();
}

public void getLocation()
{

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    locationListener = new MyLocationListener();

    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0,locationListener);
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);    
}

private OnClickListener startButtonClickListener = new OnClickListener()
{
    public void onClick(View v) {
        // TODO Auto-generated method stub
        gpsOrg=coordinates;
        totalDistanceTravel=0;
        Toast.makeText(getBaseContext(), 
                "Start Location locked : Lat: " + gpsOrg[0] + 
                " Lng: " + gpsOrg[1], 
                Toast.LENGTH_SHORT).show();

        if (!isTimerStarted)
        {
            startTimer();
            isTimerStarted = true;
        }

        stopButton.setEnabled(true);
    }
};
private OnClickListener stopButtonClickListener = new OnClickListener()
{
    public void onClick(View v) {
        // TODO Auto-generated method stub
        gpsEnd=coordinates;
        //gpsEnd = new double[2];
        //gpsEnd[0]=1.457899;
        //gpsEnd[1]=103.828659;

        Toast.makeText(getBaseContext(), 
                "End Location locked : Lat: " + gpsEnd[0] + 
                " Lng: " + gpsEnd[1], 
                Toast.LENGTH_SHORT).show();

        double d = distFrom(gpsOrg[0],gpsOrg[1],gpsEnd[0],gpsEnd[1]);
        totalDistanceTravel+=d;
        disTrav.setText(Double.toString(d));
    }
};

  public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
        double earthRadius = EARTH_RADIUS;
        double dLat = Math.toRadians(lat2-lat1);
        double dLng = Math.toRadians(lng2-lng1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                   Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                   Math.sin(dLng/2) * Math.sin(dLng/2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        double dist = earthRadius * c;

        return new Float(dist).floatValue();
        }


public class MyLocationListener implements LocationListener
{
    public void onLocationChanged(Location loc) {  
            if(coordinates!=null)
            {
                double[] coordinatesPrev=coordinates;
                double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
                totalDistanceTravel+=d;
            }
            else
            {
                coordinates = getGPS();
            }

            startButton.setEnabled(true);

    }

private double[] getGPS() {
     List<String> providers = lm.getProviders(true);

    double[] gps = new double[2];

    //Loop over the array backwards, and if you get an accurate location, then break out the loop

    Location l = null;

    for (int i=providers.size()-1; i>=0; i--) {

            String s = providers.get(i);

            Log.d("LocServ",String.format("provider (%d) is %s",i,s));

            l = lm.getLastKnownLocation(providers.get(i));  

            if (l != null) {

                    gps[0] = l.getLatitude();
                    gps[1] = l.getLongitude();

                    Log.d("LocServ",String.format("Lat %f, Long %f accuracy=%f",gps[0],gps[1],l.getAccuracy()));

                    gpsOnOff.setText("On");
            }      
    }
    return gps;
}

我的代码有什么问题吗?请提出建议,非常感谢您的帮助:)

最佳答案

用这个测试你的公式:{-73.995008, 40.752842} 和 {-73.994905, 40.752798} 之间的距离应该是 0.011532248670891638 公里。

关于java - Android - 使用 Haversine 公式计算距离(使用 GPS、Lat 和 Long),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7523905/

相关文章:

java - 计算二维数组内的曼哈顿距离

java - maven如何使用mvn compile找出文件被更改的内容

java - Google Drive V3 中 eTag 字段的替代方案?

java - Android解析json响应中的特殊字符

java - 简单的 Selenium 正则表达式 Java

android - 从editText中删除光标

android - 在不使用 ContentProvider 的情况下保留单例数据库旋转数据(Android)

android - 等待线程会破坏线程的目的吗? Android 线程问题

algorithm - 按到端节点的距离对图进行排序

linux - 使用 Bash 计算今天和当月下一个重复日期之间的距离?