Android 獲取位置資訊(經緯度)(附程式碼)
阿新 • • 發佈:2018-11-28
獲取位置資訊主要通過GPS和網路位置兩種方法,優先順序還是GPS,有點就不多說了,下面說一下我做的方法及附程式碼,有疑問可在下方留言。
思路便是GPS優先,但在GPS訊號弱的情況下采取拿網路位置來彌補的方法,儘量做到次次上傳都有位置資訊傳上去。
private String getLngAndLat(Context context) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { //從gps獲取經緯度 Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } else {//當GPS訊號弱沒獲取到位置的時候又從網路獲取 return getLngAndLatWithNetwork(); } } else { //從網路獲取經緯度 locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } return longitude + "," + latitude; } //從網路獲取經緯度 public String getLngAndLatWithNetwork() { double latitude = 0.0; double longitude = 0.0; LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener); Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } return longitude + "," + latitude; }