I want to convert 4.5 km to mile in depending on the user's location.
Is it possible in Android?
In iOS I can use something like
fileprivate let _distanceFormatter =
MKDistanceFormatter()_distanceFormatter.string(fromDistance: model.distanse)
I want to convert 4.5 km to mile in depending on the user's location.
Is it possible in Android?
In iOS I can use something like
fileprivate let _distanceFormatter =
MKDistanceFormatter()_distanceFormatter.string(fromDistance: model.distanse)
Is it possible in Android? YES
1 Km = 0.621371 Miles.
You can make a helper function from the above formula.
public float convertKmsToMiles(float kms){
float miles = 0.621371 * kms;
return miles;
}
Pass your Kms value to this function and you will get the Miles value for it. :)
float miles = convertKmsToMiles(4.5);
I don't think there's necessarily a correct answer for all locales. For example, in the UK they generally use miles for large distances like a car journey, feet and inches for people's height but may use meters to describe the dimensions of a room.
You can try to do something like this: Using locale settings to detect wheter to use imperial units
or you can just give the user the option to choose a preferred unit in a settings menu.
Hope it helps.
My understanding is that OP wants to be able to convert a given distance to Miles or Kilo-meters depending on the user's location. For example if user is in America, the distance should be in Miles by default, not in Km nor Yard nor Ft, or if the user is in Europe the distance should be in Km by default, not anything else unless specified.
To answer OP question, you can use the Geocoder api to achieve what you're tryna do. Simply, get user location data,then use the Geocoder class/object to get the user's country name and finally you create a function to display/convert the distance.
Remember
implementation 'com.google.android.gms:play-services-location:17.0.0'
Here's how you could use it in this instance.
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>
To test this out, I used the emulator GPS to select a country, and based on the country the distance will be displayed either in Miles or Km.
To learn more, refer to this Google API documentation on Location