Android:如何在连续移动时找到使用GPS覆盖的总距离?

时间:2013-03-06 19:32:44

标签: android gps distance locationmanager

这是我的代码。请告诉我,它无法计算距离。在此代码中res是一个长变量,应该存储所覆盖的总距离。这个代码应该在纬度和经度发生变化时立即根据GPS计算距离。

String serviceString = Context.LOCATION_SERVICE;
LocationManager locationManager;
locationManager= (LocationManager)getSystemService(serviceString);

String provider = LocationManager.GPS_PROVIDER;
final Location loc1=locationManager.getLastKnownLocation(provider);
//Location loc1=new Location("");

String netprovider=LocationManager.NETWORK_PROVIDER;

lat1=loc1.getLatitude();
lon1=loc1.getLongitude();               

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

                            Location loc2=new Location("");
                            lat2=loc2.getLatitude();
                            lon2=loc2.getLongitude();
                            dtvalue.setText(lat1+","+lon1+","+lat2+","+lon2);

                            Location.distanceBetween(lat1,lon1,lat2,lon2,dist);
                            res=res+(long)dist[0];

                            lat1=lat2;
                            lon1=lon2;
                        }
                        public void onProviderDisabled(String provider)
                        {
                            // Update application if provider disabled.
                        }
                        public void onProviderEnabled(String provider)
                        {
                            // Update application if provider enabled.
                        }
                        public void onStatusChanged(String provider, int status,
                                Bundle extras)
                        {
                            // Update application if provider hardware status changed.
                        }
                    };
locationManager.requestLocationUpdates(provider, 5000, 1, myLocationListener);
locationManager.requestLocationUpdates(netprovider, 5000, 1, myLocationListener);

1 个答案:

答案 0 :(得分:3)

您要定义空位置Location loc2=new Location("");然后使用它的问题。

您可以在班级中定义lat1lon1

public void onLocationChanged(Location loc1) 
{

    if(lat1 != 0 && long1 != 0) { 
       Location.distanceBetween(lat1,lon1,loc1.getLatitude(),loc1.getLongitude(),dist);
       res+=(long)dist[0];
    }

    lat1=loc1.getLatitude();
    lon1=loc1.getLongitude();
}