GPS Lat,一次又一次地对同一当前位置进行长时间更换

时间:2016-02-23 09:51:57

标签: android gps

我正在努力寻找设备的速度。我正在使用速度公式获得各种好处。但我有一个问题。如果我把Mobile放在同一个地方,然后几秒后它的位置改变,还有速度,距离等,我会得到不同的lat。 我希望如果设备没有运行,那么它只显示一个当前lat,long(speed = 0)没有不同,因为位置没有变化。 我正在使用这个课程:

public class GPSTracker extends Service implements LocationListener 
{
 boolean first_time=true;
private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;

// flag for network status
boolean isNetworkEnabled = false;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

double prev_lat=0.0;
double prev_long=0.0;
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES =  0;// meters  (make the time and distance to 0,0 so that we could get the updates very quickly
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; //  minute

// Declaring a Location Manager
protected LocationManager locationManager;

int hour1=0;
int minute1=0;
int second1=0;
int hour2=0;
int minute2=0;
int second2=0;

int time_dif=0;

private static float distance=0;
static double speed=0;

public GPSTracker(Context context) 
{
    this.mContext = context;
    getLocation();
}

public Location getLocation()
{
    try 
    {
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
        // getting GPS status
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // getting network status
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!isGPSEnabled && !isNetworkEnabled) 
        {
            Toast.makeText(getApplicationContext(), "Either Network or GPS is not available in your Mob " , Toast.LENGTH_LONG).show();
            // no network provider is enabled
        } 
        else 
        {
            this.canGetLocation = true;

            // if GPS Enabled get lat/long using GPS Services
            /*if (isNetworkEnabled)              
            {
                  //Update the location of a user after t time and d distance... where we have declared time and distance as 0,0 which means to get frequent updates.
            locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                if (locationManager != null) 
                {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        //Toast.makeText(getApplicationContext(), "Location "+location.getLatitude() , Toast.LENGTH_LONG).show();   
                    }
                } 
            }
            //*/
            //else if (isGPSEnabled)
             if (isGPSEnabled)
            {   //Toast.makeText(getApplicationContext(), "inside 'isGpdenabled' " , Toast.LENGTH_LONG).show();
                if (location == null) 
                {
                    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
            //*/
        }

    } catch (Exception e) 
    {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS()
{
    if(locationManager != null)
    {
        locationManager.removeUpdates(GPSTracker.this);
    }       
}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}


/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() 
{
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enable. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

//((((( Find distance between two geolocation  )))
public float FindDistance(float lat1, float lng1, float lat2, float lng2)
    {
         double earthRadius = 6371000; //meters
            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));
            float dist = (float) (earthRadius * c);

            return dist;

    }


public double Set_Speed_inKM()
{
    speed=speed*3.6;   // Formula to Convert M/Sec --> KM/Sec

    return speed;
}

@Override
public void onLocationChanged(Location location) 
{
  if(!first_time )
  {

  if( prev_lat!=location.getLatitude() & prev_long!=location.getLongitude())
    {
    //showtoast("Location Changed");
    Calendar c = Calendar.getInstance();
    second1=c.get(Calendar.SECOND);     

    if(second2>second1)
        second1=60+second1;

      time_dif=second1-second2;       
      time_dif=Math.abs(time_dif);


    second2=second1;

     distance=FindDistance((float)prev_lat,(float)prev_long,(float)location.getLatitude(),(float)location.getLongitude());

     if(time_dif!=0)
      speed=distance/time_dif;

     Set_Speed_inKM();

        Log.e("LOCATION CHANGED", "data"+location.getLatitude()+"\n");

            //Calling Function and Passing Value
          sendMessageToActivity(location ,time_dif,"NewLocation", this.mContext);

            //prev_lat=location.getLatitude();
          //  prev_long=location.getLongitude();

        }
     }
         prev_lat=location.getLatitude();
        prev_long=location.getLongitude();

        first_time=false;
    }


//((( This Function SEND data 2 ACTIVITY )))))))
private static void sendMessageToActivity(Location l,float time_diff, String msg, Context c) 
{
    Intent intent = new Intent("GPSLocationUpdates");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", l);
    intent.putExtra("Location", b);
    intent.putExtra("speed", ""+speed);
    intent.putExtra("time_diff", ""+distance);
    LocalBroadcastManager.getInstance(c).sendBroadcast(intent);
}


@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

//Show-Toast Message
public void showtoast(String str)
{
//  Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
}

}

1 个答案:

答案 0 :(得分:1)

GPS的准确性并不是绝对的,因此即使是静态设备也会在连续读数中显示不同的位置。您可以通过读取加速度计来添加检测移动设备是否静止的方法 - 如果两个读数之间的差值大于某个阈值 - 设备正在移动。如果它太小 - 它不会移动。要确定增量 - 将设备放在桌子上并查看您获得的值。