如何从android设备获取纬度和经度



我有一个应用程序已经在请求运行时权限来激活本地化权限,我已经准备好接收经度和纬度了。我现在的问题只是从设备本身获取纬度和经度。

这是我的方法,假设该方法转到else语句,因为我已经拥有处理工作的权限

if (!checkPermissions()) {
requestPermissions()
} else {
//get latitude and long here
}

这是一个示例代码

1.LocationManager&侦听器

private LocationManager locationManager;
private LocationListener locationListener;

2.设置管理器&侦听器

locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
String locationProvider = LocationManager.GPS_PROVIDER;
currentLocation = locationManager.getLastKnownLocation(locationProvider);
if (currentLocation != null) {
double lng = currentLocation.getLongitude();
double lat = currentLocation.getLatitude();
Log.d("Log", "longtitude=" + lng + ", latitude=" + lat);
}

最新更新