React Native [4] – Expo Location

라이브러리 설치

expo에서 제공하는 라이브러리를 사용한다.

$ expo install expo-location

소스코드

import { Alert, StyleSheet, Text, View } from 'react-native';
import React,{ useEffect, useState,Component } from 'react';
import * as Location from 'expo-location';
  
export default function HomeScreen() {
    //변수선언
    const [ok,setOk] = useState(true);
    const [city,setCity] = useState();
    const [country,setConuntry] = useState();
    const [district,setDistrict] = useState();
    const [region,setRegion] = useState();
    const [street,setStreet] = useState();
    const [streetNumber,setStreetNumber] = useState();
    
    //권한 요청 및 위치정보 가져오는 AsyncFunction
    const checkPermission = async () => {
        
        try {
             //권한요청
            const {granted} = await Location.requestForegroundPermissionsAsync();
                if(!granted){
                    setOk(false);
                }
                // 위치정보 가져오기
                const {coords:{latitude,longitude}} = await Location.getCurrentPositionAsync();
                const location = await Location.reverseGeocodeAsync({latitude,longitude},{useGoogleMaps:false});
                console.log(location);
                setCity(location[0].city);
                setConuntry(location[0].country);
                setDistrict(location[0].district);
                setRegion(location[0].region);
                setStreet(location[0].street);
                setStreetNumber(location[0].streetNumber);
            }catch(e){
                Alert.alert("위치정보를 가져올 수 없습니다.");
            }
    };

    //권한 AsyncFunction 실행
    useEffect(() => {
        checkPermission();
    },[]);

    
    return {
        <View>
        <Text>MainScreen</Text>
        <Text>{city}</Text>
        </View>
    );
}

Leave a Comment