[React Native] Location, ActivityIndicator

gigi·2022년 7월 19일
0

Location

현재 위치의 기온과 날씨를 텍스트로 간단히 보여주는 앱을 만드는 과정에서 유용한 Location API를 사용해 보았다.
Location은 현재 디바이스의 위치정보를 가져올 수 있다. 모바일 특성 상 다양한 장소에서 접속이 가능 하기 때문에 위치정보를 기반으로 하는 앱에서 필수적인 기능이다.

먼저 프로젝트에 Location을 설치해준다.

expo install expo-location

App.js

import * as Location from "expo-location";
import { useEffect, useState } from "react";
import { StyleSheet, View, Text } from "react-native";

export default function App() {
  const [cityName, setCityName] = useState("");
  const [accept, setAccept] = useState(true);

  const getWeather = async () => {
    const { granted } = await Location.requestForegroundPermissionsAsync();
    if (!granted) {
      setAccept(false);
    }

    const { coords: { latitude, longitude },} = await Location.getCurrentPositionAsync({ accuracy: 5 });

    const location = await Location.reverseGeocodeAsync({ latitude, longitude,}, { sueGoogleMaps: false });

    setCityName(location[0].city);
  };

  useEffect(() => {
    getWeather();
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.text}>{cityName}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",

    backgroundColor: "orange",
  },
  text: {
    fontSize: 50,
  },
});
  • requestForegroundPermissionsAsync : 앱이 실행중인 동안 위치에 대한 권한을 부여하도록 사용자에게 요청한다. 요청을 승인한 경우 granted = true가 된다.
  • getCurrentPositionAsync : 현재 디바이스 접속 위치의 위도, 경도 데이터를 반환한다. (latitude, longitude)
    option으로 위치정확도와 관련된 accuracy를 줄 수 있다.(1 : 3km, 2 : 1km, 3 : 100m, 4 : 10m, 5 : 제일높은 정확도, 6 : 추가 센서 데이터를 사용하는 가능한 최고의 정확도)
  • reverseGeocodeAsync : 위도, 경도 정보를 바탕으로 해당 좌표의 주소를 반환한다.

이외에도 다양한 기능들을 알아보려면 아래 웹사이트를 참고하면 된다.
https://docs.expo.dev/versions/v45.0.0/sdk/location/

ActivityIndicator

로딩상태를 나타내주는 컴포넌트

react-native 에서 ActivityIndicator 를 import 한 후, 필요한 곳에 쓰면 된다. Location 코드에서 컴포넌트의 return문만 변경 되었다. cityName을 가져오기 전까지 ActivityIndicator 컴포넌트 화면을 띄워준다.

import * as Location from "expo-location";
import { useEffect, useState } from "react";
import { ActivityIndicator, StyleSheet, View, Text } from "react-native";

export default function App() {
  const [cityName, setCityName] = useState("");
  const [accept, setAccept] = useState(true);

  const getWeather = async () => {
    const { granted } = await Location.requestForegroundPermissionsAsync();
    if (!granted) {
      setAccept(false);
    }

    const { coords: { latitude, longitude },} = await Location.getCurrentPositionAsync({ accuracy: 5 });

    const location = await Location.reverseGeocodeAsync({ latitude, longitude,}, { sueGoogleMaps: false });

    setCityName(location[0].city);
  };
  
  useEffect(() => {
    getWeather();
  }, []);

  return (
    <View style={styles.container}>
  // ****************************** 변경부분 ******************************
      {!cityName ? (
        <ActivityIndicator size="large" color="tomato" />
      ) : (
        <Text style={styles.text}>{cityName}</Text>
      )}
 // *********************************************************************
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",

    backgroundColor: "orange",
  },
  text: {
    fontSize: 50,
  },
});

0개의 댓글