我需要一种简单获取纬度和经度的方法。我正在开发我的第一个应用程序......你能否告诉我,我是否以正确的方式做到了这一点?
这是我的方法:
private void getCoordinates() {
getCurrentLocation();
boolean gpsEnabled = lManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean netEnabled = lManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gpsEnabled && !netEnabled && location != null) {
Builder alarm = new AlertDialog.Builder(this);
alarm.setTitle("Error");
alarm.setMessage("Localization OFF").create().show();
} else if (location != null && (gpsEnabled || netEnabled)) {
lManager.removeUpdates(lListener);
lat = String.valueOf(location.getLatitude());
lon = String.valueOf(location.getLongitude());
} else {
Builder alarm = new AlertDialog.Builder(this);
alarm.setTitle("Error");
alarm.setMessage("Localization OFF").create().show();
}
}
private void getCurrentLocation() {
lManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
lListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location loc) {
location = loc;
}
};
LocationProvider gpsProvider = lManager.getProvider(LocationManager.GPS_PROVIDER);
if (gpsProvider != null) {
boolean gpsEnabled = lManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean netEnabled = lManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!gpsEnabled && netEnabled) {
lManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, lListener);
location = lManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else if (gpsEnabled) {
lManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lListener);
location = lManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
} else {
Builder alarm = new AlertDialog.Builder(this);
alarm.setTitle("Error");
alarm.setMessage("GPS provider not supported").create().show();
}
}
如果您发现任何错误或给我任何建议,请修理它。
答案 0 :(得分:0)
问题是当您为该位置设置侦听器时,它不会立即收到位置 - 尤其是GPS位置。因此,您的位置不会返回当前坐标。 您可以在位置管理器中调用getLastKnownLocation,但这可能是旧的或不存在的位置。另一种选择是从
调用一些东西@Override public void onLocationChanged(Location loc) { someCallBack(loc); }
在github上查看我的NoteLocation示例 Link