【问题标题】:GPS Lat, Long change for same current location again and againGPS Lat, Long 一次又一次地改变相同的当前位置
【发布时间】:2016-02-23 20:46:57
【问题描述】:

我正在尝试查找设备的速度。我使用速度公式得到了一切好处。但我有一个问题。如果我把手机放在同一个地方,我会得到不同的纬度,几秒钟后它的位置会改变,速度和距离等也会改变。 我希望如果设备没有运行,那么它只显示一个当前的纬度,长(速度 = 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();
}

}

【问题讨论】:

  • 我只看到一个问题...您使用了 来自 androidhive 的非常糟糕的代码 ...服务不需要上下文,因为它本身就是一个上下文...您也不能从您的代码中调用服务派生类的新运营商...但是关于您所谓的问题:MIN_DISTANCE_CHANGE_FOR_UPDATES = 0 + GPS 不准确的事实导致“位置变化”...您不应该为此烦恼变化非常小(小于 GPS 的精度)...
  • @Selvin 谢谢,但请告诉我在哪里更改代码,我真的被困在里面了
  • everthing ...但即使没有这个糟糕的代码...它也会以相同的方式工作...将 MIN_DISTANCE_CHANGE_FOR_UPDATES 更改为至少 5 那么你不应该得到更改...
  • @Selvin 为什么整个代码不适合获取 gps lat、long?
  • 因为它取自 androidhive ......错误代码的来源......为了 FSM 我已经写了为什么这个代码不好(这里至少有 10 个问题使用这个(再次)非常糟糕的代码)

标签: android gps


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-02
    • 2015-08-04
    • 2015-07-04
    • 2013-05-24
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    相关资源
    最近更新 更多