프론트/React Native, React

[리액트 네이티브]react-native 현재 위치 가져오기

연지양갱 2023. 6. 19. 00:30
728x90
반응형
SMALL

일단 처음이기 때문에 니콜라스 쌤 수업을 들으면서 진행하려고 한다!

 

#2.8 Weather (15:32) – 노마드 코더 Nomad Coders

 

All Courses – 노마드 코더 Nomad Coders

초급부터 고급까지! 니꼬쌤과 함께 풀스택으로 성장하세요!

nomadcoders.co

 

이 영상을 보면서 따라했다!

 

필수!!

expo install expo-location

 

 

<App.js>

import * as Location from "expo-location";
import { StatusBar } from "expo-status-bar";
import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  Dimensions,
  ActivityIndicator,
  StyleSheet,
  ScrollView,
} from "react-native";
import { Fontisto } from "@expo/vector-icons";

const { width: SCREEN_WIDTH } = Dimensions.get("window");

const API_KEY = "784ab24ff2ed5d94d4288abed9e25d13";

const icons = {
  Clouds: "cloudy",
  Clear: "day-sunny",
  Atmosphere: "cloudy-gusts",
  Snow: "snow",
  Rain: "rains",
  Drizzle: "rain",
  Thunderstorm: "lightning",
};

export default function App() {
  const [city, setCity] = useState("Loading...");
  const [days, setDays] = useState([]);
  const [ok, setOk] = useState(true);
  const getWeather = async () => {
    const { granted } = await Location.requestForegroundPermissionsAsync();
    if (!granted) {
      setOk(false);
    }
    const {
      coords: { latitude, longitude },
    } = await Location.getCurrentPositionAsync({ accuracy: 5 });
    const location = await Location.reverseGeocodeAsync(
      { latitude, longitude },
      { useGoogleMaps: false }
    );
    setCity(location[0].city);
    const response = await fetch(
      `https://api.openweathermap.org/data/2.5/onecall?lat=${latitude}&lon=${longitude}&exclude=alerts&appid=${API_KEY}&units=metric`
    );
    const json = await response.json();
    setDays(json.daily);
  };
  useEffect(() => {
    getWeather();
  }, []);
  return (
    <View style={styles.container}>
      <StatusBar style="light" />
      <View style={styles.city}>
        <Text style={styles.cityName}>{city}</Text>
      </View>
      <ScrollView
        pagingEnabled
        horizontal
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.weather}
      >
        {days.length === 0 ? (
          <View style={{ ...styles.day, alignItems: "center" }}>
            <ActivityIndicator
              color="white"
              style={{ marginTop: 10 }}
              size="large"
            />
          </View>
        ) : (
          days.map((day, index) => (
            <View key={index} style={styles.day}>
              <View
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  width: "100%",
                  justifyContent: "space-between",
                }}
              >
                <Text style={styles.temp}>
                  {parseFloat(day.temp.day).toFixed(1)}
                </Text>
                <Fontisto
                  name={icons[day.weather[0].main]}
                  size={68}
                  color="white"
                />
              </View>

              <Text style={styles.description}>{day.weather[0].main}</Text>
              <Text style={styles.tinyText}>{day.weather[0].description}</Text>
            </View>
          ))
        )}
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "tomato",
  },
  city: {
    flex: 1.2,
    justifyContent: "center",
    alignItems: "center",
  },
  cityName: {
    fontSize: 58,
    fontWeight: "500",
    color: "white",
  },
  weather: {},
  day: {
    width: SCREEN_WIDTH,
    alignItems: "flex-start",
    paddingHorizontal: 20,
  },
  temp: {
    marginTop: 50,
    fontWeight: "600",
    fontSize: 100,
    color: "white",
  },
  description: {
    marginTop: -10,
    fontSize: 30,
    color: "white",
    fontWeight: "500",
  },
  tinyText: {
    marginTop: -5,
    fontSize: 25,
    color: "white",
    fontWeight: "500",
  },
});

 

위 코드를 실행하기 전에

install을 해줘야 한다!

expo install expo-location

 

 

 

위도 경도까지 알수 있음!

이것도 써서 서버에 보내고 막 이러쿵 저러쿵 쓰면 될거 같다!

app 키를 받으면 좋은 데ㅔ

그냥 쓰고 싶은걸요ㅎㅎㅎㅎ,,,,

위 코드는 날씨 정보까지 가져온다!

https://dev-yakuza.posstree.com/ko/react-native/react-native-geolocation-service/

 

React Native에서 현재 위치 정보 가져오기

react-native-geolocation-service 라이브러리를 이용하여 React Native에서 현재 위치 정보를 가져오는 방법에 대해서 알아봅시다.

dev-yakuza.posstree.com

 

https://dlee0129.tistory.com/32

 

[React Native] GeoLocation 사용법 / 현재 위치 정보 불러오기

React Native GeoLocation 사용법 / 현재 위치 정보 불러오기 현재 위치 정보를 알 수 있는 쉽고 편하며 무료인 GeoLocation API 소개와 사용법입니다. 이 API를 사용하여 현재 위치의 위도와 경도를 알 수 있

dlee0129.tistory.com

 

https://www.univdev.page/posts/react-native-tracking/

 

[React Native] 유저 위치 트래킹

개요 가끔 어플리케이션을 만들 때 사용자의 위치를 추적해야 하는 경우가 있습니다. 주변 맛집을 찾아주거나, 운전 중 도로 상황을 알려주기 위한 어플리케이션을 제작할 때를 예로 들 수 있는

www.univdev.page

 

https://e-hyun.tistory.com/7

 

[React Native] 디바이스의 현재 위치 가져오기

React Native 의 개발환경을 세팅하고 Expo 에 대한 설명은 아래를 참고! [React Native] Hello World! 개발환경 세팅하기 [React Native] Hello World! 개발환경 세팅하기 React Native 를 시작하게 된 계기 일전에 ios 도

e-hyun.tistory.com

 

 

 


 

이게 제일 좋아보임!

https://velog.io/@flowersayo/React-NativeExpo%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-GPS-%EC%9C%84%EC%B9%98%EC%B6%94%EC%A0%81-%EB%9F%AC%EB%8B%9D-%ED%8A%B8%EB%9E%98%ED%82%B9-%EC%95%B1-%EB%A7%8C%EB%93%A4%EA%B8%B0

 

React Native(Expo)를 이용한 GPS 위치추적 - 러닝 트래킹 앱 만들기

우리팀원분중 한명이 만든 플로깅화면의 프로토타입이다. 조깅하면서 쓰레기를 줍는 활동을 장려하는 어플이기 때문에 플로깅을 흥미있어할 수 있도록 사용자의 위치를 실시간으로 추적하면

velog.io

 

 

직접 코드를 짜기 전에 찾아봤던 자료들이다

반응형