使用GPS获取当前位置

时间:2014-02-23 13:08:35

标签: android gps

我希望能够仅使用GPS获取当前坐标。

目前我的代码获取一次坐标,然后在存储后再次使用它们。我正在寻找有关如何修改代码的解决方案,以便在单击按钮时获取当前坐标。

以下是代码:

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

    //Setting TextViews for the coordinates
    startLatitudeField = (TextView) findViewById(R.id.TextView02);
    startLongitudeField = (TextView) findViewById(R.id.TextView04);
    endLatitudeField = (TextView) findViewById(R.id.textView06);
    endLongitudeField = (TextView) findViewById(R.id.textView08);


    //Button
    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {


            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            provider = locationManager.getBestProvider(criteria, false);
            Location location = locationManager.getLastKnownLocation(provider);
            //find out how to get the current location using gps
            //not what is stored

            if (startLat != 0) {
                onLocationChanged(location);
            } else {
            onLocationChanged(location);
            Button button = (Button) findViewById(R.id.button1);
            button.setText("Get me home");
            }


        }


    }); 
};

@Override
public void onLocationChanged(Location location) {

    if (startLat == 0) {
        startLat = (double) (location.getLatitude());
        startLng = (double) (location.getLongitude());
        startLatitudeField.setText(String.valueOf(startLat));
        startLongitudeField.setText(String.valueOf(startLng));
    } 
    else {

        endLat = (double) (location.getLatitude());
        endLng = (double) (location.getLongitude());
        endLatitudeField.setText(String.valueOf(endLat));
        endLongitudeField.setText(String.valueOf(endLng));
    }

}

2 个答案:

答案 0 :(得分:2)

首先,您需要向Manifest文件添加权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

你在stackoverflow中得到的答案是: How do I get the current GPS location programmatically in Android?

这里有一个示例应用: http://www.rdcworld-android.blogspot.in/2012/01/get-current-location-coordinates-city.html

答案 1 :(得分:0)

https://developer.android.com/training/location/retrieve-current.html 检查一下,他们还提供了示例代码