简体   繁体   中英

How to get the user preferred units? Meters or Miles

I am developing an app in react native and I would like to display some distance to my users.

As I live in Europe, I have used the "Kilometers" systems but I would like to know my user settings for this metrics so I could display the value with the correct unit.

I already used this module : https://github.com/react-native-community/react-native-device-info

But it does not seem to have this functionality.

Do you know some module that have? Or a quick way to link some native function?

Thank you in advance

As already suggested in the comments, you ca use react-native-device-info . See below, for a working example:

  transformDistance(distanceKM) {
    const countryCode = DeviceInfo.getDeviceCountry(); // get country code 
    const factor = 0.621371; // constant scale factor: 1km = 0.621371 miles
    if (countryCode == "US") {
      return <Text> {distanceKM * factor} Miles </Text>;
    } 
    // add other countries as additional if statements here 
    //

    //otherwise return distance in metric unit
    return <Text> {distanceKM} Km </Text>;
  }

  render() {
    return (
      <View style={styles.container}>
        <View>
     {this.transformDistance(5)} // outputs 3.106855 Miles or 5 Km
        </View>
      </View>
    );
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM