[React Native] Expo Location 활용

Nadan
Nadan Dev Blog

Expo Location 활용

-> 내가 사용했던 예제로 변경

검색

참고

● 권한 Flow 이해하기

● 권한 Reset 하기

  • ios simulator : Settings > General > Reset > Reset Location and Privacy
  • ios Device : Settings > Expo > Toggle Permission
  • Android Emulator : adb shell pm reset-permissions
  • Android Device : Settings > Applications > Expo > Toggle Permission

● 권한 Reset 하기

mainia 블로그 참고

1) expo-location 설치

expo install expo-location

2) Location 권한 받아오기

Map.js

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

3) 현재 위치 가져오기

subscriber = await Location.watchPositionAsync({ -> 여기에 await 빼먹으면 Promise가 리턴되서 remove를 호출할 수 없음

import * as Location from 'expo-location';

await Location.watchPositionAsync({
    accuracy: Location.Accuracy.BestForNavigation,
    timeInterval: 1000,
    distanceInterval: 10,
}, (location) => {
    // 시뮬레이터의 mock 위치 때문에 우회
    if (location.coords.latitude === 37.58295 ||
        location.coords.longitude === 127.0537) return;
    callback(location);
});

4) 현재 위치 변경(mock location)

_mockLocation에서 _getCurrentWatchId()이거 두번이나 애먹음… → malformed size 에러 뜸

react native malformed calls from js field sizes are different

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: 127.053706 + increment * tenMetersWithDegrees,
            latitude: 37.582950 + increment * tenMetersWithDegrees
        }
    };
};

let counter = 0;

setInterval(() => {
    Location.EventEmitter.emit('Expo.locationChanged', {
        watchId: Location._getCurrentWatchId(),
        location: getLocation(counter)
    });
    counter++;
}, 1000);