Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GET CURRENT WEATHER FOR USER LOCATION
function getCurrentWeather(lat, lng) {
var json = getCurrentConditions(lat, lng);
var obj = JSON.parse(json);
var currentWeather = obj.currentobservation.Weather;
var tempF = obj.currentobservation.Temp;
var currentWindSpeed = obj.currentobservation.Winds;
var currentWindDirection = obj.currentobservation.Windd;
var currentWindGust = obj.currentobservation.Gust;
var currentHumidity = obj.currentobservation.Relh;
var currentPressure = obj.currentobservation.SLP;
var currentStation = obj.currentobservation.name;
var currentStationElev = obj.currentobservation.elev;
var currentWindChill = obj.currentobservation.WindChill;
var forecastPeriod = obj.time.startPeriodName[0];
var forecastText = obj.data.text[0];
var allWeatherStr = (currentWeather + "||" + tempF + "||" + currentWindSpeed+ "||" + currentWindDirection+ "||" + currentWindGust+ "||" + currentHumidity+ "||" + currentPressure+ "||" + currentStation+ "||" + currentStationElev+ "||" + currentWindChill+ "||" + forecastPeriod+ "||" + forecastText);
return allWeatherStr;
}
function getCurrentConditions(lat, lng) {
var url = "https://forecast.weather.gov/MapClick.php?lat=" + lat + "&lon=" + lng + "&FcstType=json";
var resp;
var xmlHttp;
resp = "" ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0");
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp;
}
@ordashevsky
Copy link

ordashevsky commented Jul 2, 2021

For Android replace getCurrentConditions() function with following

function getCurrentConditions(lat, lng) {
var url = "https://forecast.weather.gov/MapClick.php?lat=" + lat + "&lon=" + lng + "&FcstType=json";
var resp;
var xmlHttp;
 
    resp = "" ;
    xmlHttp = new XMLHttpRequest();
 
    if(xmlHttp != null)
    {
        xmlHttp.open( "GET", url, false );
        xmlHttp.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0");
        xmlHttp.send( null );
        resp = xmlHttp.responseText;
    }
 
    return resp;
}

@truth3
Copy link
Author

truth3 commented Jul 14, 2021

The main post has been updated to include the following line in the function to set the User-Agent request header.

xmlHttp.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:221.0) Gecko/20100101 Firefox/31.0");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment