使用GPS获取一个人步行的距离

3

大家好,我能够使用以下代码获取当前位置的经度和纬度。

我有两个按钮:开始行走停止行走

当点击开始行走按钮时,它将获取当前位置(经度和纬度),人们将从A(起始点)开始行走,并在一段时间内行走,然后返回A(现在变成目的地),之后他点击停止行走按钮。

现在我需要向用户显示以下细节:

1. 他行走的距离(以公里为单位)。

2. 他花费的时间(以分钟为单位)。

(可选)3. 速度或平均速度。

**

获取当前位置的代码

**

private EditText editTextShowLocation;
    private Button buttonGetLocation;
    private ProgressBar progress;

    private LocationManager locManager;
    private LocationListener locListener = new MyLocationListener();

    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);

        progress = (ProgressBar) findViewById(R.id.progressBar1);
        progress.setVisibility(View.GONE);

        buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
        buttonGetLocation.setOnClickListener(this);

        locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        progress.setVisibility(View.VISIBLE);
        // exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled) {
            AlertDialog.Builder builder = new Builder(this);
            builder.setTitle("Attention!");
            builder.setMessage("Sorry, location is not determined. Please enable location providers");
            builder.setPositiveButton("OK", this);
            builder.setNeutralButton("Cancel", this);
            builder.create().show();
            progress.setVisibility(View.GONE);
        }

        if (gps_enabled) {
            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
        }
        if (network_enabled) {
            locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
        }
    }

    class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                // This needs to stop getting the location data and save the battery power.
                locManager.removeUpdates(locListener); 

                String londitude = "Londitude: " + location.getLongitude();
                String latitude = "Latitude: " + location.getLatitude();
                String altitiude = "Altitiude: " + location.getAltitude();
                String accuracy = "Accuracy: " + location.getAccuracy();
                String time = "Time: " + location.getTime();

                editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
                progress.setVisibility(View.GONE);
            } 
        }

        @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

        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(which == DialogInterface.BUTTON_NEUTRAL){
            editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
        }else if (which == DialogInterface.BUTTON_POSITIVE) {
            startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }

如何实现这个目标。

类似问题:- https://dev59.com/SmHVa4cB1Zd3GeqPmmyB#9662506 - Scorpion
3个回答

8

试试这个

public class TestActivity extends Activity implements Runnable {
 private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 30000;

    protected LocationManager locationManager;
    static double n=0;
    Long s1,r1;
    double plat,plon,clat,clon,dis;
    MyCount counter;
    Thread t1;
    EditText e1;
    boolean bool=true;

Button b1,b2,b3,b4,b5;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    b1=(Button)findViewById(R.id.button1);<--- current position
    b2=(Button)findViewById(R.id.button2);<---- start moving.. calculates distance on clicking this
    b3=(Button)findViewById(R.id.button3);<--- pause
    b4=(Button)findViewById(R.id.button4);<-- resume
    b5=(Button)findViewById(R.id.button5);<-- get distance
    e1=(EditText)findViewById(R.id.editText1);
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MINIMUM_TIME_BETWEEN_UPDATES, 
            MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
            new MyLocationListener()
    );
    b1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            showCurrentLocation();
        }
});     

}
protected void showCurrentLocation() {

    Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        String message = String.format(
                "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );
        clat=location.getLatitude();
        clon=location.getLongitude();
        Toast.makeText(TestActivity.this, message,
                Toast.LENGTH_LONG).show();
    }
    else{
        Toast.makeText(TestActivity.this, "null location",
                Toast.LENGTH_LONG).show();
    }

}
public void start (View v){

    switch(v.getId()){

    case R.id.button2:
        t1=new Thread();
        t1.start();
        counter= new MyCount(30000,1000);
     counter.start();
     break;
    case R.id.button3:
        counter.cancel();
        bool=false;
        break;
    case R.id.button4:
        counter= new MyCount(s1,1000);
     counter.start();
     bool=true;
     break;
    case R.id.button5:

        double time=n*30+r1;
        Toast.makeText(TestActivity.this,"distance in metres:"+String.valueOf(dis)+"Velocity in m/sec :"+String.valueOf(dis/time)+"Time :"+String.valueOf(time),Toast.LENGTH_LONG).show();

    }


}


private class MyLocationListener implements LocationListener {

    public void onLocationChanged(Location location) {
        String message = String.format(
                "New Location \n Longitude: %1$s \n Latitude: %2$s",
                location.getLongitude(), location.getLatitude()
        );

        Toast.makeText(TestActivity.this, message, Toast.LENGTH_LONG).show();
    }

    public void onStatusChanged(String s, int i, Bundle b) {
        Toast.makeText(TestActivity.this, "Provider status changed",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderDisabled(String s) {
        Toast.makeText(TestActivity.this,
                "Provider disabled by the user. GPS turned off",
                Toast.LENGTH_LONG).show();
    }

    public void onProviderEnabled(String s) {
        Toast.makeText(TestActivity.this,
                "Provider enabled by the user. GPS turned on",
                Toast.LENGTH_LONG).show();
    }

}
public class MyCount extends CountDownTimer{
    public MyCount(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    }
    @Override
    public void onFinish() {
        counter= new MyCount(30000,1000);
     counter.start();
     n=n+1;
    }
    @Override
    public void onTick(long millisUntilFinished) {
        s1=millisUntilFinished;
        r1=(30000-s1)/1000;
        e1.setText(String.valueOf(r1));


    }
    }
@Override
public void run() {
    while(bool){
  clat=location.getLatitude();
        clon=location.getLongitude();
        if(clat!=plat || clon!=plon){
            dis+=getDistance(plat,plon,clat,clon);
            plat=clat;
            plon=clon;

        }

    }

}

计算距离的函数...

public double getDistance(double lat1, double lon1, double lat2, double lon2) {
    double latA = Math.toRadians(lat1);
    double lonA = Math.toRadians(lon1);
    double latB = Math.toRadians(lat2);
    double lonB = Math.toRadians(lon2);
    double cosAng = (Math.cos(latA) * Math.cos(latB) * Math.cos(lonB-lonA)) +
                    (Math.sin(latA) * Math.sin(latB));
    double ang = Math.acos(cosAng);
    double dist = ang *6371;
    return dist;
}

}


1
你能分享一下计算距离的想法吗?我的意思是使用上述代码的逻辑。 - Vikky
有很多方法可以计算距离。不同的方法有不同的优缺点(性能与准确性)。这个被称为Haversine公式:en.wikipedia.org/wiki/Haversine_formula 这里还有一些其他公式:movable-type.co.uk/scripts/latlong.html Haversine公式被认为是准确的。 - Joakim Sandqvist

7
首先,这更像是一个问题询问并得到答案的过程。本论坛上的人不会为你做工作。
现在介绍一种实现你所需的方法。
你需要使用一个服务来跟踪用户和位置。简单的方法是将mytracks服务作为应用程序的插件或者使用mytracks代码创建自己的跟踪服务。 http://code.google.com/p/mytracks/ 你可以查看:http://code.google.com/p/mytracks/w/list

非常抱歉,我尝试了很多次寻找答案,但是没有找到。 - Goofy
嘿,http://code.google.com/p/mytracks/wiki/MyTracksApi 这是我需要参考的代码吗? - Goofy
你不需要道歉,但是不要因为有人没有为你编写所有代码而创建更多问题。你已经提供了几个示例和操作指南。至于MyTracks,请查看维基百科。要么使用他们的服务并导入库,要么自己创建服务。我不会替你完成这项工作。 - David Olsson
它只跟踪用户移动的情况并记录距离,用户可以是在跑步、开车等。如果您想定义速度等参数,可能需要编写自己的服务。因此,请下载mytracks源代码并查看。它有很好的文档说明。 - David Olsson
嘿,我知道这是为Android 4.0设计的,但我正在使用Android 2.2。 - Goofy
显示剩余3条评论

1
通过使用distanceTo()函数,你可以计算两个地理位置之间的距离。
Location destination =new Location("gps");
destination.setLatitude(lat);
destination.setLongitude(lng);
float dist=user_location.distanceTo(destination);


1
请查看以下链接以获取更多详细信息:http://developer.android.com/reference/android/location/Location.html#distanceTo%28android.location.Location%29 - Jaiprakash Soni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接