Android应用程序在textViews中显示lat long

时间:2015-12-10 05:19:01

标签: android latitude-longitude

我试图在textView上显示纬度和经度,但它似乎并没有起作用。 lat和long将通过模拟器控件发送,当我尝试发送值时,它应该在textViews上显示它们但它似乎不起作用,也许我错过了什么?

public class MainActivity extends Activity implements View.OnClickListener{

//Defining views
private EditText editTextLatitude;
private EditText editTextLongitude;
private EditText editTextTimeInserted;
LocationManager lm;
TextView lt, ln;
String provider;
Location l;
private Button buttonAdd;
private Button buttonView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Initializing views
    editTextLatitude = (EditText) findViewById(R.id.editTextLat);
    editTextLongitude = (EditText) findViewById(R.id.editTextLon);
    editTextTimeInserted = (EditText) findViewById(R.id.editTextTimeInserted);

    buttonAdd = (Button) findViewById(R.id.buttonAdd);
    buttonView = (Button) findViewById(R.id.buttonView);

    //Setting listeners to button
    buttonAdd.setOnClickListener(this);
    buttonView.setOnClickListener(this);
    ln = (TextView) findViewById(R.id.lng);
    lt = (TextView) findViewById(R.id.lat);
    lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    Criteria c = new Criteria();

    provider = lm.getBestProvider(c, false);

    l = lm.getLastKnownLocation(provider);

    if (l != null) {     //get latitude and longitude of the location
        double lng = l.getLongitude();
        double lat = l.getLatitude();
        //display on text view
        ln.setText("" + lng);
        lt.setText("" + lat);
    } else {
        ln.setText("No Provider");
        lt.setText("No Provider");
    }
}

1 个答案:

答案 0 :(得分:1)

让您的活动实现LocationListener

implements LocationListener

然后在onCreate

中请求locationUpdates
lm.requestLocationUpdates(provider, 20000, 0, this);

然后在你的onLocationChanged方法中,覆盖实现LocationListener一旦发送位置就更新你的textViews

@Override
public void onLocationChanged(Location location) {
    double lng = location.getLongitude();
    double lat = location.getLatitude();
    //display on text view
    ln.setText("" + lng);
    lt.setText("" + lat);    
}