[React Native] Location 활용
Nadan Dev Blog
Location
Location 이해
권한 요청
import React, { useEffect, useState } from 'react';
import { requestPermissionAsync } from 'expo-location';
const TrackCreateScreen = () => {
const [err, setErr] = useState('');
const startWatching = async () => {
try {
await requestPermissionAsync();
} catch (e) {
console.log(e);
setErr(e);
}
}
useEffect(() => {
startWatching();
}, [])
return (
<SafeAreaView>
<Text h2>TrackCreateScreen</Text>
<Map />
{err ? <Text>Please enable loaction services</Text> : null}
</SafeAreaView>
);
};
권한 수정
테스트용 위치 설정
테스트 위치 설정이 예상대로 되지 않을 수 있음
코드로 location을 변경해준다.
_mockLocation.js
import * as Location from 'expo-location';
const tenMetersWithDegrees = 0.0001;
const getLocation = increment => {
return {
timestamp: 1000000,
coords: {
speed: 0,
heading: 0,
accuracy: 5,
altitudeAccuracy: 5,
altitude: 5,
longitude: -122.0312186 + increment + tenMetersWithDegrees,
latitude: 37.33233141 + increment + tenMetersWithDegrees
}
};
};
let counter = 0;
setInterval(() => {
Location.EventEmitter.emit('Expo.locationChanged', {
watchId: Location._getCurrentWatchId(),
location: getLocation(counter)
});
counter++;
}, 1000);
TrackCreateScreen.js
import '../_mockLocation';
...
import { requestPermissionsAsync, watchPositionAsync, Accuracy } from 'expo-location';
const TrackCreateScreen = () => {
const [err, setErr] = useState('');
const startWatching = async () => {
try {
await requestPermissionsAsync();
await watchPositionAsync({
accuracy: Accuracy.BestForNavigation,
timeInterval: 1000,
distanceInterval: 10
}, (location) => {
console.log(location);
});
} catch (e) {
console.log(e);
setErr(e);
}
}
useEffect(() => {
startWatching();
}, [])
return (
<SafeAreaView>
<Text h2>TrackCreateScreen</Text>
<Map />
{err ? <Text>Please enable loaction services</Text> : null}
</SafeAreaView>
);
};
const styles = StyleSheet.create({});
export default TrackCreateScreen;