1

我有以下代码:

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_GPSlat, tv_GPSlon) 但位置值不是恒定的(它们一直在变化)。我怎样才能做到这一点?

4

4 回答 4

0

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

于 2013-01-20T00:56:32.107 回答
0

您必须获得该位置,并且一旦获得它(即调用您的处理程序方法),您必须取消注册处理程序才能停止接收更新。onLocationChanged()只需在处理程序方法的末尾添加这一行MyLocationListener

LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocManager.removeUpdates(this);
于 2013-01-27T02:56:55.217 回答
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
于 2013-01-27T03:12:52.313 回答
0

我想知道为什么没有人提到这一点。可能是我错过了什么。您拨打的电话有 0,0。它应该有毫秒,距离米。这种方式位置更改仅在经过特定距离或超时后调用。我同时使用 GPS 和 NETWORK 提供程序,以不依赖于任何一个(有时 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);
于 2013-01-27T04:16:09.670 回答