我的理解是,OP 希望能够将给定距离转换为英里或千米 取决于 strong> 用户的位置。
例如,如果用户在美国,则默认距离应以英里为单位,而不是以公里、码或英尺为单位,或者如果用户在欧洲,则距离应默认以公里为单位,除非另有说明。
要回答 OP 问题,您可以使用 Geocoder api 来实现您想要做的事情。
很简单,获取用户位置数据,然后使用 Geocoder 类/对象获取用户的国家名称,最后创建一个函数来显示/转换距离。
记住
- 将此添加到您的 build.gradle(应用程序模块,而不是项目模块)中,以便您可以使用位置服务
implementation 'com.google.android.gms:play-services-location:17.0.0'
- 为了访问用户 GPS 数据,您需要一个 fusedLocationClient。
在这种情况下你可以如何使用它。
ExampleFragment.kt
class ExampleFragment : Fragment() {
private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var textView: TextView
private lateinit var geocoder: Geocoder
// test locations
val eiffelTower : Location = Location("et").apply {
latitude = 48.858093
longitude = 2.294694
}
val empireStateBulding : Location = Location("esb").apply {
latitude = 40.748817
longitude = -73.985428
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? {
val root = inflater.inflate(R.layout.fragment_explore, container, false)
textView = root.findViewById(R.id.text_home)
/* Let's initialize the fused location client in order
to get user location data via gps means */
fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity())
// initialize the geocoder
geocoder = Geocoder(requireContext())
val button: Button = root.findViewById(R.id.button)
button.setOnClickListener {
getLocationData()
}
return root
}
private fun getLocationData() {
/* get or check user's permission to so your app
can have access to the user location */
if (ActivityCompat.checkSelfPermission(requireActivity(),
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(requireActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
/* if the above permissions are not granted
we request them. Request code 101 is a random number. */
ActivityCompat.requestPermissions(requireActivity(),
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
), 101)
}
// get user current location from the client's and do some work..
fusedLocationClient.lastLocation
.addOnSuccessListener { currentLocation ->
val currentCountryName = getCountryName(currentLocation)
val distance: Int = currentLocation.distanceTo(eiffelTower).roundToInt()
val distanceToDisplay = getDistanceToDisplay(currentCountryName, distance)
val textToDisplay =
"""Distance to Eiffel Tower is: ${distanceToDisplay}
|Your current country is: ${currentCountryName}
""".trimMargin()
textView.text = textToDisplay
}
}
private fun getCountryName(location: Location): String {
/* the getFromLocation() provides a list of address,
where we pick the first address item and
return the countryName property or No found country if null */
return geocoder.getFromLocation(location.latitude, location.longitude, 1)
.first()
.countryName ?: "No country found"
}
private fun getDistanceToDisplay(currentCountryName: String, distance: Int): String {
// you can add more cases in here, these are for brevity
return when (currentCountryName) {
"France" -> " ${distance} meters"
"USA", "United States" -> " ${distance / 1609} miles "
else -> "Intl Unit : ${distance}m"
}
}}
fragment_example.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ExampleFragment">
<TextView
android:id="@+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:lines="3"
android:maxLines="4"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get my location"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_home" />
</androidx.constraintlayout.widget.ConstraintLayout>
为了测试这一点,我使用模拟器 GPS 选择了一个国家,并根据国家/地区以英里或公里显示距离。
示例 1
示例 2
要了解更多信息,请参阅此Google API documentation on Location