ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [weather_app_5] api에서 정보를 가져와서 적용하기
    프로젝트/[react]weather_app 2018. 4. 29. 16:04

    사용할 날씨 api => openWeatherMap


    https://openweathermap.org/api


    Current weather data 를 subscribe

    가입해야함. key를 얻자

    const API_KEY = "apiKey"






    api doc (https://openweathermap.org/current)

    By geographic coordinates

    API call:

    api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}


    _getWeather = (lat, lng) => {
    fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&APPID=${API_KEY}`)
    .then(response => response.json())
    .then(json => {
    console.log(json)
    })
    }




    ${lat}

    $ 붙혀줘야하고 fetch할때 ' 가 아닌 tap 위의 키로 감싸줘야함  - > `






    weather code와 온도 가져오기

    state = {
    isLoaded: false,
    error: null,
    temperature: null,
    name: null
    };


    temp와 name의 위치는 console.log(json)으로 확인


    _getWeather = (lat, lng) => {
    fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&APPID=${API_KEY}`)
    .then(response => response.json())
    .then(json => {
    this.setState({
    temperature: json.main.temp,
    name: json.weather[0].main,
    isLoaded: true
    })
    })
    }






    리팩토링

    stateless컴포넌트로


    // export default class Weather extends Component {
    // render() {
    // return (
    // <LinearGradient
    // colors={["#00C6FB", "#005BEA"]} //from-to 색상 지정
    // style={styles.container} //스타일
    // >
    // <View style={styles.upper}>
    // <Ionicons color="white" size={144} name="ios-rainy" />
    // <Text style={styles.temp}>25˚</Text>
    // </View>
    // <View style={styles.lower}>
    // <Text style={styles.title}>Rainning</Text>
    // <Text style={styles.subtitle}>For more info look outside</Text>
    // </View>
    // </LinearGradient>
    // );
    // }
    // }

    function Weather(){
    return(
    <LinearGradient
    colors={["#00C6FB", "#005BEA"]} //from-to 색상 지정
    style={styles.container} //스타일
    >
    <View style={styles.upper}>
    <Ionicons color="white" size={144} name="ios-rainy" />
    <Text style={styles.temp}>25˚</Text>
    </View>
    <View style={styles.lower}>
    <Text style={styles.title}>Rainning</Text>
    <Text style={styles.subtitle}>For more info look outside</Text>
    </View>
    </LinearGradient>
    )
    }

    export default Weather;





    props주기

    app.js

    const { isLoaded, error, temperature } = this.state;


    {isLoaded ? <Weather temp={temperature} /> : (



    weather.js

    import PropTypes from 'prop-types';

    function Weather({ temp }){
    return(
    <LinearGradient
    colors={["#00C6FB", "#005BEA"]} //from-to 색상 지정
    style={styles.container} //스타일
    >
    <View style={styles.upper}>
    <Ionicons color="white" size={144} name="ios-rainy" />
    <Text style={styles.temp}>{temp}˚</Text>
    </View>
    <View style={styles.lower}>
    <Text style={styles.title}>Rainning</Text>
    <Text style={styles.subtitle}>For more info look outside</Text>
    </View>
    </LinearGradient>
    );
    }

    Weather.propTypes = {
    temp: PropTypes.number.isRequired
    }



    캘빈을 변경하기

    내림처리


    {isLoaded ? <Weather temp={Math.floor(temperature - 273.15)} /> : (





    name

    https://openweathermap.org/weather-conditions


    const weatherCases = {
    Rain: {
    colors:["#00C6FB", "#005BEA"],
    title: "Raining",
    subtitle: "우산 챙기세요",
    icon: "ios-rainy"
    },
    Clear: {
    colors:["#FEF253", "#FF7300"],
    title: "Sunny",
    subtitle: "날이 좋아요",
    icon: "ios-sunny"
    },
    Thunderstorm: {
    colors:["#00ECBC", "#007ADF"],
    title: "Thunderstrom",
    subtitle: "천둥이쳐요!",
    icon: "ios-thunderstorm"
    },
    Clouds: {
    colors:["#D7D2CC", "#304352"],
    title: "Clouds",
    subtitle: "구름이 꼈어요",
    icon: "ios-cloudy"
    },
    Snow: {
    colors:["#7DE2FC", "#B9B6E5"],
    title: "Snow",
    subtitle: "눈이와요!",
    icon: "ios-snow"
    },
    Drizzle: {
    colors:["#89F7FE", "#66A6FF"],
    title: "Drizzle",
    subtitle: "이슬비가 내려요",
    icon: "ios-rainy-outline"
    },
    Haze: {
    colors:["#89F7FE", "#66A6FF"],
    title: "Haze",
    subtitle: "이슬비가 내려요",
    icon: "ios-rainy-outline"
    },
    Mist: {
    colors:["#89F7FE", "#66A6FF"],
    title: "Mist",
    subtitle: "이슬비가 내려요",
    icon: "ios-rainy-outline"
    }
    }


    강의에는 Mist가 없는데 지금 날씨가 Mist라 오류.. Mist 따로 정의해줬다!




    function Weather({ weatherName , temp }){
    return(
    <LinearGradient
    colors={weatherCases[weatherName].colors} //from-to 색상 지정
    style={styles.container} //스타일
    >
    <View style={styles.upper}>
    <Ionicons color="white" size={144} name={weatherCases[weatherName].icon} />
    <Text style={styles.temp}>{temp}˚</Text>
    </View>
    <View style={styles.lower}>
    <Text style={styles.title}>{weatherCases[weatherName].title}</Text>
    <Text style={styles.subtitle}>{weatherCases[weatherName].subtitle}</Text>
    </View>
    </LinearGradient>
    );
    }



    App.js 에서는 props를 넘겨줘야함

    render() {
    const { isLoaded, error, temperature, name } = this.state;
    return (
    <View style={styles.container}>
    <StatusBar hidden={true} />
    {isLoaded ? <Weather weatherName={name} temp={Math.floor(temperature - 273.15)} /> : (
    <View style={styles.loading}>
    <Text style={styles.LoadingText}>Getting the weather</Text>
    {error ? <Text style={styles.errorText}>{error}</Text> : null}
    </View>
    )}
    </View>
    );
    }


    댓글

Designed by Tistory.