현재 위치의 기온과 날씨를 텍스트로 간단히 보여주는 앱을 만드는 과정에서 유용한 Location API를 사용해 보았다.
Location은 현재 디바이스의 위치정보를 가져올 수 있다. 모바일 특성 상 다양한 장소에서 접속이 가능 하기 때문에 위치정보를 기반으로 하는 앱에서 필수적인 기능이다.
먼저 프로젝트에 Location을 설치해준다.
expo install expo-location
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,
},
});
이외에도 다양한 기능들을 알아보려면 아래 웹사이트를 참고하면 된다.
https://docs.expo.dev/versions/v45.0.0/sdk/location/
로딩상태를 나타내주는 컴포넌트
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,
},
});