如何使用 android studio 获取当前位置
how to get current Location with android studio
我想获取当前位置,然后我在应用程序中按了一个按钮,但它没有给我那个,而是给了我未知的地址,但是如果我将我的位置更改为美国,它会提供地址吗?我没有收到任何错误,一切正常,只是地址没有显示?这是我的代码,如果你能帮助我,我将不胜感激。
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(currentLocation.getCoordinates().latitude, currentLocation.getCoordinates().longitude, 1);
if (addresses.isEmpty()) {
autocompleteFragmentFrom.setText(R.string.waiting_for_location);
} else {
addresses.size();
if (addresses.get(0).getThoroughfare() == null) {
pickupLocation.setName(addresses.get(0).getLocality());
} else if (addresses.get(0).getLocality() == null) {
pickupLocation.setName("unknown address");
} else {
pickupLocation.setName(addresses.get(0).getLocality() + ", " + addresses.get(0).getThoroughfare());
}
autocompleteFragmentFrom.setText(pickupLocation.getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
enter image description here
请求位置权限并启用 GPS 后使用 FusedLocationProviderClient。
private val mFusedLocationProviderClient: FusedLocationProviderClient by lazy {
LocationServices.getFusedLocationProviderClient(requireActivity())
}
mFusedLocationProviderClient.lastLocation?.addOnSuccessListener(this) { location:Location? ->
val lat = location?.latitude
val lon = location?.longitude
}
我想获取当前位置,然后我在应用程序中按了一个按钮,但它没有给我那个,而是给了我未知的地址,但是如果我将我的位置更改为美国,它会提供地址吗?我没有收到任何错误,一切正常,只是地址没有显示?这是我的代码,如果你能帮助我,我将不胜感激。
try {
Geocoder geo = new Geocoder(this.getApplicationContext(), Locale.getDefault());
List<Address> addresses = geo.getFromLocation(currentLocation.getCoordinates().latitude, currentLocation.getCoordinates().longitude, 1);
if (addresses.isEmpty()) {
autocompleteFragmentFrom.setText(R.string.waiting_for_location);
} else {
addresses.size();
if (addresses.get(0).getThoroughfare() == null) {
pickupLocation.setName(addresses.get(0).getLocality());
} else if (addresses.get(0).getLocality() == null) {
pickupLocation.setName("unknown address");
} else {
pickupLocation.setName(addresses.get(0).getLocality() + ", " + addresses.get(0).getThoroughfare());
}
autocompleteFragmentFrom.setText(pickupLocation.getName());
}
} catch (IOException e) {
e.printStackTrace();
}
}
enter image description here
请求位置权限并启用 GPS 后使用 FusedLocationProviderClient。
private val mFusedLocationProviderClient: FusedLocationProviderClient by lazy {
LocationServices.getFusedLocationProviderClient(requireActivity())
}
mFusedLocationProviderClient.lastLocation?.addOnSuccessListener(this) { location:Location? ->
val lat = location?.latitude
val lon = location?.longitude
}