How Do I Get Geolocation In Openweather Api
How do I get mu openweather API to work with geolocation? This is my current html code: ;
$.getJSON(getIP).done(function(location) {
console.log(location)
})
Next get WeatherData from OpenWeatherMap service using the ip-api that we got above
var getIP = 'http://ip-api.com/json/';
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'
$.getJSON(getIP).done(function(location) {
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
units: 'metric',
APPID: 'APIKEY'
}).done(function(weather) {
console.log(weather)
})
})
In this case, the celsius temperature (metric)
Or using HTML5 Geolocation API (in Google Chrome work only with HTTPS
or on localhost
)
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'if (window.navigator && window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(function(position) {
$.getJSON(openWeatherMap, {
lat: position.coords.latitude,
lon: position.coords.longitude,
units: 'metric',
APPID: 'APIKEY'
}).done(function(weather) {
console.log(weather)
})
})
}
Solution 2:
Lets try it , I hope that is a better solution to get current weather via using geolacation and Openweather API . Simply pass your Openweather API Key , you will get a json array, fetch your location and current weather. And you also use your weather icon which you want.
window.addEventListener("load",() =>{
let long;
let lag;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition((position) =>{
var lat = position.coords.latitude;
var long = position.coords.longitude;
const proxy = "https://cors-anywhere.herokuapp.com/";
const api = `${proxy}api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=9891731b361e47661f72b06213efbf65`;
fetch(api)
.then((response) =>{
return response.json();
})
.then(data =>{
const {name} = data;
const {feels_like} = data.main;
const {id,main} = data.weather[0];
loc.textContent = name;
climate.textContent = main;
tempValue.textContent = Math.round(feels_like-273);
if(id < 250){
tempIcon.src = './icon/storm.svg'
}
elseif(id < 350){
tempIcon.src = './icon/drizzle.svg'
}
elseif(id < 550){
tempIcon.src = './icon/rain.svg'
}
elseif(id < 650){
tempIcon.src = './icon/snow.svg'
}
elseif(id < 800){
tempIcon.src = './icon/atmosphere.svg'
}
elseif(id === 800){
tempIcon.src = './icon/clear.svg'
}
elseif(id >800){
tempIcon.src = './icon/clouds.svg'
}
console.log(data);
})
})
}
})
Post a Comment for "How Do I Get Geolocation In Openweather Api"