我想根据用户的位置将4.5公里转换为英里 在Android中可以吗?
在iOS中我可以使用类似
的内容fileprivate let _distanceFormatter =
MKDistanceFormatter()_distanceFormatter.string(fromDistance: model.distanse)
答案 0 :(得分:3)
在Android中可以吗? 是
1 Km = 0.621371英里。
您可以使用上面的公式创建辅助函数。
public float convertKmsToMiles(float kms){
float miles = 0.621371 * kms;
return miles;
}
将您的Kms值传递给此函数,您将获得它的里程值。 :)
float miles = convertKmsToMiles(4.5);
答案 1 :(得分:0)
我不认为所有语言环境都必须是正确的答案。例如,在英国,他们通常使用英里长距离,例如汽车旅行,英尺和英寸的高度,但可以用米来描述房间的尺寸。
您可以尝试执行以下操作: Using locale settings to detect wheter to use imperial units
或者您可以让用户选择在设置菜单中选择首选单位。
希望它有所帮助。
答案 2 :(得分:0)
我的理解是,OP希望能够转换给定距离为英里或千米 依赖用户位置上的“ strong”。 例如,如果用户在美国,则默认情况下,距离应以英里为单位,而不是Km,Yard或Ft;如果用户在欧洲,则默认情况下应以Km为单位,除非另有说明。
要回答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"
}
}}
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选择了一个国家/地区,然后根据该国家/地区以英里或公里显示距离。
要了解更多信息,请参阅此Google API documentation on Location