React Native GeoLocation 사용법 / 현재 위치 정보 불러오기
현재 위치 정보를 알 수 있는 쉽고 편하며 무료인 GeoLocation API 소개와 사용법입니다.
이 API를 사용하여 현재 위치의 위도와 경도를 알 수 있습니다.
도시의 이름 등 city와 관련된 정보는 없지만, 위도와 경도만으로도 다른 API와 혼합하여 사용하기 충분하기에 많은 쓰임세가 있는 API라고 할 수 있습니다.
우선 설치입니다. 저는 version 0.59 이상을 기준으로 소개해드릴 것입니다.
react native 버전 0.59 이상을 사용하신 분들은 아래 명령어를 사용하시면 됩니다.
npm install @react-native-community/geolocation --save
다음은 권한 설정 permission입니다.
안드로이드는 android > app > main > AndroidManifest.xml 을 열어
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
위의 권한설정 코드를 추가해 주셔야 합니다.
iOS의 경우 별도의 추가 작업이 필요없습니다.
info.plist에 NSLocationWhenInUseUsageDescription 다음의 권한이 필요한데,
react-native init을 해줄 때, 즉 프로젝트 생성시 자동으로 추가가 됩니다.
<key>NSLocationWhenInUseUsageDescription</key>
<string/>
확인하시고 없으시다면, 추가해주시면 됩니다.
이제 간단한 Test 앱 입니다.
Get GeoLocation을 누르면 권한 정보가 필요하다 알림이 오며,
권한 허용을 해준 다음, 다시 누르시면 현재 위도와 경도가 화면에 표시됩니다.
import React, { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Geolocation from '@react-native-community/geolocation';
import { TouchableOpacity } from 'react-native-gesture-handler';
const GeoLocationAPI = ({
}) => {
const [latitude, setLatitude] = useState(null);
const [longitude, setLogitude] = useState(null);
const geoLocation = () => {
Geolocation.getCurrentPosition(
position => {
const latitude = JSON.stringify(position.coords.latitude);
const longitude = JSON.stringify(position.coords.longitude);
setLatitude(latitude);
setLogitude(longitude);
},
error => { console.log(error.code, error.message); },
{enableHighAccuracy:true, timeout: 15000, maximumAge: 10000 },
)
}
return (
<View>
<Text> latitude: {latitude} </Text>
<Text> longitude: {longitude} </Text>
<TouchableOpacity onPress={() => geoLocation()}>
<Text> Get GeoLocation </Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}
})
export default GeoLocationAPI;
react native hooks functional component 형식을 사용하였습니다.
Geolocation.getCurrentPosition함수를 사용하시면 현재 위치 정보와 관련된 JSON 파일을 return 리턴 받으시는데, 그 중 저는 위도와 경도만 parsing 파싱하여 사용하였습니다.
좀 더 정확한 위치 정보 등을 원하시면 enableHighAccuracy 부분을 수정하시면 됩니다.
'웹, 앱 개발 > RN React-Native' 카테고리의 다른 글
[React Native] Hooks를 이용한 Timer functional component (0) | 2021.02.06 |
---|---|
[React Native] MacBook M1 Run Android Emulator 안드로이드 에뮬레이터 구동 (0) | 2021.02.03 |
[React Native] react-native-timeline-flatlist API (0) | 2021.02.01 |
[React Native] ImageBackground borderRadius (0) | 2021.02.01 |
[React Native] Keyboard.dismiss 빈공간 클릭시 키보드 사라지게 (0) | 2021.01.30 |