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