-2
我需要一種方法來簡單地獲取經度和緯度。我正在開發我的第一個應用程序...你能告訴我,如果我以正確的方式做到這一點嗎?如何通過GPS和/或網絡獲取緯度和經度?
這裏是我的方法:
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();
}
}
請修復它,如果你能看到什麼毛病,或給我任何建議。
可能重複[如何以編程方式獲取當前GPS位置的Android?] (http://stackoverflow.com/questions/1513485/how-do-i-get-the-current-gps-location-programmatically-in-android) – Simas 2014-10-12 14:06:30
這裏沒有什麼用處,只回答一些關於GPS的答案和其他答案是不完整 – smartmouse 2014-10-12 14:34:54
有什麼特定的東西在你的代碼中不起作用嗎? – Simas 2014-10-12 14:36:08