2014-02-23 220 views
0

我希望能够仅使用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)); 
    } 

} 
+0

如果您需要获得点击按钮的坐标,那么为什么还需要'onLocationChanged'? – mangusta

+0

不确定。我正在跟随一个指导,并将其与我拥有的一点知识结合在一起。如果我知道答案,我会说... – Bob21

回答

2

所有你需要的权限添加到清单文件的第一:

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

你在这里有答案在计算器: 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

+0

感谢您的支持。我已经获得了该许可。 – Bob21

+0

因此,示例工作? –

+0

我得到了基础,但需要帮助让它正常工作。 这里是与答案,如果你想查看它的帖子:http://stackoverflow.com/questions/21988087/gps-app-runs-but-shuts-down-on-button-click?answertab =活动#标签-最佳 – Bob21