Skip to content

Instantly share code, notes, and snippets.

@dinizgb
Created August 23, 2021 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dinizgb/6af12fc20e9e722924f42f37c35a5973 to your computer and use it in GitHub Desktop.
Save dinizgb/6af12fc20e9e722924f42f37c35a5973 to your computer and use it in GitHub Desktop.
//Clone the full project on: https://github.com/dinizgb/nextjs-weather-widget-with-styled-components
import React, { useState, useEffect } from "react";
import Image from 'next/image';
import styled from 'styled-components';
const WeatherWidgetWrapper = styled.div`
min-width: 250px;
background: #fff;
border: 1px solid #e8eaff;
border-radius: 6px;
padding: 15px 15px 0 15px;
margin: 20px;
`
const WidgetTitle = styled.h1`
font-size: 16px;
font-weight: bold;
color: #666;
`
const IconArea = styled.div`
padding: 0 5px;
`
const TempText = styled.div`
font-size: 30px;
font-weight: bold;
color: #666;
margin-top: 24px;
`
export default function WeatherWidget_LatLon() {
const [weather, setWeather] = useState({});
useEffect(() => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
fetchWeather(position.coords.latitude, position.coords.longitude);
});
const fetchWeather = async (latitude, longitude) => {
try{
const weatherReq = await fetch(`https://api.weatherapi.com/v1/forecast.json?key=ee94006c9bb74ce892f181126211305&q=${latitude},${longitude}&days=1&aqi=no&alerts=no`);
const weatherData = await weatherReq.json();
setWeather({icon: <Image src={"https:" + weatherData.current.condition.icon} alt={`It is ${weatherData.current.temp_c} in your city`} width={80} height={80} />, temperature: weatherData.current.temp_c + "º C"});
}
catch{
console.log("xWthErr");
}
};
}
}, []);
return (
<WeatherWidgetWrapper>
<div className="row">
<WidgetTitle>With Latitude and Longitude</WidgetTitle>
</div>
<div className="row">
<IconArea>{weather.icon}</IconArea>
<TempText>{weather.temperature}</TempText>
</div>
</WeatherWidgetWrapper>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment