2013-01-20 48 views
1

我有以下代码:如何获得持续的GPS位置

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
LocationListener mlocListener = new MyLocationListener(); 
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener); 

MyLocationListener类:

public class MyLocationListener implements LocationListener{ 

     @Override 
     public void onLocationChanged(Location loc){ 
     loc.getLatitude(); 
     loc.getLongitude(); 
     tv_GPSlat.setText("Latitude: " + loc.getLatitude()); 
     tv_GPSlon.setText("Longitude: " + loc.getLongitude()); 
     } 

     @Override 
     public void onProviderDisabled(String provider){ 
     Toast.makeText(getApplicationContext(),"GPS is not working", Toast.LENGTH_SHORT).show(); 
     } 

     @Override 
     public void onProviderEnabled(String provider){ 
     Toast.makeText(getApplicationContext(),"GPS is working",Toast.LENGTH_SHORT).show(); 
     } 

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

我想目前的经度和纬度保存到我的TextView S(tv_GPSlattv_GPSlon)但位置值不是恒定的(它们一直在变化)。我怎样才能做到这一点?

回答

0

GPS并不准确 - 即使您不移动它也会反弹一下。只要把你得到的第一个位置,并忽略未来的更新,除非他们的移动超过一定数量。这是最简单的方法。

+0

但如何做到这一点? – Sharpowski

+0

使用Location.distanceTo()比较发送给您的新结果与上一个结果。如果距离小于您想要的任何阈值,请忽略更新。 –

+0

我想保存第一个显示的位置(经度和纬度)尽可能变量,但我不知道如何。 – Sharpowski

0

你必须得到位置,一旦你得到它(即你的处理程序方法被调用),你必须取消注册处理程序以停止接收更新。只需在您的处理方法onLocationChanged()月底在MyLocationListener加入这一行:

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
mlocManager.removeUpdates(this); 
0

数据成员添加到您的位置监听器,并保持先前​​的位置吧:

public class MyLocationListener implements LocationListener { 

    public Location mSavedLocation; 

    @Override 
    public void onLocationChanged(Location loc) { 
     // If we don't have saved location, or the distance between 
     // the saved location and the new location is bigger than 
     // 5 meters (~15ft) save the new location 
     if ((mSavedLocation == null) || 
      (loc.distanceTo(mSavedLocation) > 5)) { 
      mSavedLocation = loc; 
     } 
     // Update the screen with the current saved location 
     tv_GPSlat.setText("Latitude: " + mSavedLocation.getLatitude()); 
     tv_GPSlon.setText("Longitude: " + mSavedLocation.getLongitude()); 
    } 

    // ... no changes to the rest of the class 
} 

现在的其余部分您的代码也可以使用以下最新的保存位置:

mlocListener.mSavedLocation 
0

我想知道为什么没有人提到这一点。可能是我缺少一些东西。你所做的电话有0,0。它应该有毫秒,distanceinmeters。这种方式的位置改变只在特定距离行进或在超时之后被调用。我正在使用GPS和网络提供商也不依赖于(有时GPS不可靠)。

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, God.KM20TIME, 
      God.KM20DISTANCE, (LocationListener) updates); 
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, God.KM20TIME, 
      God.KM20DISTANCE, (LocationListener) updates);