我想根据用户的位置将 4.5 公里转换为英里。
在安卓中可以吗?
在 iOS 中,我可以使用类似的东西
fileprivate let _distanceFormatter =
MKDistanceFormatter()_distanceFormatter.string(fromDistance: model.distanse)
我想根据用户的位置将 4.5 公里转换为英里。
在安卓中可以吗?
在 iOS 中,我可以使用类似的东西
fileprivate let _distanceFormatter =
MKDistanceFormatter()_distanceFormatter.string(fromDistance: model.distanse)
在安卓中可以吗? 是的
1 公里 = 0.621371 英里。
您可以从上面的公式中创建一个辅助函数。
public float convertKmsToMiles(float kms){
float miles = 0.621371 * kms;
return miles;
}
将您的 Kms 值传递给此函数,您将获得 Miles 值。:)
float miles = convertKmsToMiles(4.5);
我认为不一定对所有语言环境都有正确的答案。例如,在英国,他们通常使用英里来表示距离很远的距离,例如汽车行程,英尺和英寸来表示人们的身高,但可能会使用米来描述房间的尺寸。
您可以尝试执行以下操作: 使用区域设置来检测是否使用英制单位
或者您可以让用户在设置菜单中选择首选单位。
希望能帮助到你。
我的理解是,OP 希望能够根据用户的位置将给定的距离转换为英里或千米 。例如,如果用户在美国,则默认距离应以英里为单位,而不是以公里、码或英尺为单位,或者如果用户在欧洲,则距离应默认以公里为单位,除非指定,否则不要使用其他任何值。
要回答 OP 问题,您可以使用 Geocoder api 来实现您想要做的事情。简单地说,获取用户位置数据,然后使用 Geocoder 类/对象获取用户的国家名称,最后创建一个函数来显示/转换距离。
记住
implementation 'com.google.android.gms:play-services-location:17.0.0'
这是在这种情况下如何使用它的方法。
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"
}
}}
片段示例.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 来选择一个国家,然后根据国家,距离将以英里或公里显示。
要了解更多信息,请参阅有关位置的 Google API 文档