17
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-02-23

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 });
  });
}

動くサンプルはこちら↓

使い方

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の文脈で現在地を取るのは楽だなあ。。。。

17
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?