Help us understand the problem. What is going on with this article?

React Nativeで現在地をもらってくる

More than 1 year has passed since last update.

React Nativeでの現在地の取り方について。自分用メモ。

AndroidとiOSとWebのすべてに対応すると考えるにしても、ざっくりこれでいいかなって。

async function getCurrentPosition(timeoutMillis = 10000) {
  if (Platform.OS === "android") {
      const ok = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
      if (!ok) {
          const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
          if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
              // TODO ユーザーにGPS使用許可がもらえなかった場合の処理
              throw new Error();
          }
      }
  }

  return new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition(resolve, reject, { timeout: timeoutMillis });
  });
}

動くサンプルはこちら↓

https://github.com/Nkzn/RNGeolocationSample

使い方

async componentDidMount() {
  try {
    const position = await getCurrentPosition(5000);
    const { latitude, longitude } = position.coords;
    this.setState({
      coords: {
        latitude,
        longitude
      }
    })
  } catch(e) {
    alert(e.message)
  }
}

render() {
  return (
    <View style={styles.container}>
      { this.state.coords ? <Text>here: {this.state.coords.latitude}, {this.state.coords.longitude}</Text> : null }
    </View>
  );
}

感想

Webの文脈で現在地を取るのは楽だなあ。。。。

Nkzn
新潟で農業アプリとか作ってる怪しいAndroidの人
https://blog.nkzn.info
water-cell
地球人口100億の時代への農業革命をWebテクノロジで支える
https://water-cell.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away