React Native geolocation

React Native 위치정보 받아오기

2023-10-25

React Native geolocation

사이드 프로젝트에 위치정보를 받아와야 하는 기능이 필요해 지오로케이션을 받아 오도록 했다.

설치

https://www.npmjs.com/package/react-native-geolocation-service

yarn add react-native-geolocation-service

IOS

post imagepost image

프로젝트 폴더에 swift 파일을 생성해주고 Create Bridging Header 를 선택해준다.


// ios/[projectName]/info.plist

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>서비스를 제공하는 업체 위치를 확인을 위한 위치기반 정보 서비스를 이용할 수 있습니다.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>서비스를 제공하는 업체 위치를 확인을 위한 위치기반 정보 서비스를 이용할 수 있습니다.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>서비스를 제공하는 업체 위치를 확인을 위한 위치기반 정보 서비스를 이용할 수 있습니다.</string>

post imagepost image

Android

// android/app/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

사용법

  useEffect(() => {
    if (Platform.OS === 'ios') {
      Geolocation.requestAuthorization('always');
    } else {
      PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
      ]);
    }
  }, []);

가장 많이 쓰이는 세가지 API

import Geolocation from 'react-native-geolocation-service';

const MyApp = () => {
    const [location, setLocation] = useState<ILocation | undefined>(undefined);

    useEffect(() => {
        const _watchId = Geolocation.watchPosition(
          position => {
            const {latitude, longitude} = position.coords;
            setLocation({latitude, longitude});
          },
          error => {
            console.log(error);
          },
          {
            enableHighAccuracy: true,
            distanceFilter: 0,
            interval: 5000,
            fastestInterval: 2000,
          },
        );

        return () => {
          if (_watchId) {
            Geolocation.clearWatch(_watchId);
          }
        };
      }, []);

    return <></>;
}

다음 포스팅에서는 받아온 위치정보를 webview로 넘겨주는 방법에 대해 알아보자!