You can do it with: https://www.weatherapi.com/ its FREE.
My demo is in React and step by step, but you can do it in any way you want, the key is this Weather API, that accepts LON and LAT as a string to produce city and weather info ->
https://api.weatherapi.com/v1/forecast.json?key=YOUR-KEY&q=LATITUDE,LONGITUDE&days=1&aqi=no&alerts=n
Note: you will to generate YOUR OWN KEY, by signing up
You will need 4 states for this:
const [userAllowedLocation, setUserAllowedLocation] = useState(true);
const [latitude, setLatitude] = useState("");
const [longitude, setLongitude] = useState("");
const [city, setCity] = useState("");
get Lat and Lon + pop up
First: Request access to 'location' from user (this will have a POP-UP), by using this code and set state to Latitude and Longitude.
useEffect(() => {
function getPosition() {
const successCallback = (position) => {
console.log(position);
setLatitude(position.coords.latitude);
setLongitude(position.coords.longitude);
setUserAllowedLocation(true);
};
const errorCallback = (error) => {
setUserAllowedLocation(false);
console.log(error);
};
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
}
getPosition();
}, []);
Fetch City / Country based on Lat & Lon:
Second use https://www.weatherapi.com/ API to get City and other intel, based on Lat and Lon
API looks like this: https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=53.3498053,-6.2603097&days=1&aqi=no&alerts=n
API with explanation: https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=LATITUDE,LONGITUDE&days=1&aqi=no&alerts=n
Now call this API with latitude and longitude to get location data, including city. I am using useEffect as a trigger, so as soon as I get info on Latitude I call the api using axios and set City state to what ever comes out of the api object.
useEffect(() => {
if (latitude === "" || longitude === "") { // this is to stop fetching data on component mount, cause we have no Latitude and Longitude YET
return;
}
async function getWeather() {
let res = await axios.get(
`https://api.weatherapi.com/v1/forecast.json?key=3e5e13fac8354c818de152831211305&q=${latitude},${longitude}&days=1&aqi=no&alerts=no`
);
console.log(res.data);
console.log(res.data.location.name);
setCity(res.data.location.name);
}
getWeather();
}, [latitude, longitude]);
Here is video to my youtube channel, where you can see a demo of this: https://youtu.be/gxcG8V3Fpbk
RESULT from API:
"location": {
"name": "Dublin",
"region": "Dublin",
"country": "Ireland",
"lat": 53.35,
"lon": -6.26,
"tz_id": "Europe/Dublin",
"localtime_epoch": 1673737376,
"localtime": "2023-01-14 23:02"
},