Javascript Geolocation API - javascript

Iam trying get the location of the user and than pass it to an Weather API.i need to the location and also to get the API data and insert the location to API url as a coordinates. this is my code and it isn't working :
$(document).ready(function() {
var weatherLocal;
var url = {
"apiKey": "&appid=API_KEY",
"api": "http://api.openweathermap.org/data/2.5/weather?lat=",
"units": "&units=metric",
};
function geoLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback);
}else {
console.log("not avialable");
}
}
function successCallback(position) {
url.lat = position.coords.latitude;
url.lon = position.coords.longitude;
}
function preLoader() {
var u = successCallback();
var apiUrl = url.api + u + url.apiKey + url.units;
$.getJSON(apiUrl, getData);
console.log(apiUrl);
}
function getData(data) {
weatherLocal = data;
console.log("the longitude is " + weatherLocal.coord.lon + " and the latitude is " + weatherLocal.coord.lat + " and the description is " + weatherLocal.weather[0].main + " and the city is " + weatherLocal.name + " temperature is " + weatherLocal.main.temp);
}
preLoader();
});

Related

Javascript jQuery function does not define variables

I am new to JavaScript and am trying to run a JavaScript/jQuery function, where Firefox gives me the following error:
Uncaught ReferenceError: latitude is not defined
getHighLow http://localhost:5000/static/weatherballoon.js:54
<anonymous> http://localhost:5000/static/weatherballoon.js:63
weatherballoon.js:54:5
The code being referenced is below.
function getHighLow(){
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data){
latitude = data.results[0].geometry.location.lat;
longitude = data.results[0].geometry.location.lng;
});
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat='+ latitude +'&lon='+ longitude +'&exclude={alerts,minutely,hourly}&appid='+ owmkey, function(data){
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
}```
$.getJSON() is asynchronous. You're trying to use the variables before they're set in the callback.
You need to perform the second getJSON in the first one's callback function.
function getHighLow() {
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data) {
const latitude = data.results[0].geometry.location.lat;
const longitude = data.results[0].geometry.location.lng;
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat=' + latitude + '&lon=' + longitude + '&exclude={alerts,minutely,hourly}&appid=' + owmkey, function(data) {
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
});
}
function getHighLow(){
var latitude=0;
var longitude=0;
$.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + cityID + '&key=' + geocodekey, function(data){
latitude = data.results[0].geometry.location.lat;
longitude = data.results[0].geometry.location.lng;
});
$.getJSON('https://api.openweathermap.org/data/2.5/onecall?lat='+ latitude +'&lon='+ longitude +'&exclude={alerts,minutely,hourly}&appid='+ owmkey, function(data){
var tempmin = Math.round(data.daily[0].temp.min) + '°';
var tempmax = Math.round(data.daily[0].temp.min) + '°';
document.getElementById('tempmin').innerHTML = tempmin;
document.getElementById('tempmax').innerHTML = tempmax;
});
}```

Passing Google Spreadsheet value from Google Apps script to HTML returns undefined

I am having trouble passing a value from a Google Spreadsheet to a Javascript function on the HTML.
code.gs
function getSiteCoords()
{
var emailA = Session.getActiveUser().getEmail();
var employeesheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Employees") // data pertaining to employees
var numRows=1;
while(employeesheet.getRange("A"+numRows+":A"+numRows).getValue() != "") //this will count the number of rows that are filled
{
if(employeesheet.getRange("A"+numRows).getValue()===emailA)
{
let coords = employeesheet.getRange("E"+numRows).getValue();
return coords;
}
numRows = numRows+1;
}
return "";
}
index.html
function checkPosition(position) {
console.log("Latitude: " + position.coords.latitude +
" Longitude: " + position.coords.longitude);
var lat= 54.978 ;
var long=-1.5622;
var coords = google.script.run.getSiteCoords();
console.log("Site Coords " + coords);
let calc= Math.sqrt(Math.pow(position.coords.latitude - lat , 2) + Math.pow(position.coords.longitude - long , 2));
console.log("calc: "+ calc);
if(calc>0.005)
window.location.replace("https://google.com");
}
No matter what, the coords on index.html returns undefined.

Weather API not working

Why am i not getting any data back from the weather api i am trying to update the html tag to show the temperature please help
$(document).ready(function() {
var loc = [];
console.log(loc);
$.getJSON("https://ipinfo.io?token=97f4f0d67b28dc", function(response) {
loc = response.loc.split(",");
document.getElementById("Location").innerHTML =
response.city + "," + response.country;
});
$.getJSON(
"https://fcc-weather-api.glitch.me/api/current?lat=" +
loc[0] +
"&lon=" +
loc[1],
function(data) {
console.log(data);
document.getElementById("Temperature").innerHTML = data.main.temp;
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It's because when you are calling the second request, the first isn't finished yet, so the lat long values are undefined.
You need to put your second request inside first like this:
$(document).ready(function() {
var loc = [];
$.getJSON("https://ipinfo.io?token=97f4f0d67b28dc", function(response) {
loc = response.loc.split(",");
console.log(Number(loc[0]));
document.getElementById("Location").innerHTML =
response.city + "," + response.country;
$.getJSON(
"https://fcc-weather-api.glitch.me/api/current?lat=" +
loc[0] +
"&lon=" +
loc[1],
function(data) {
console.log(data);
document.getElementById("Temperature").innerHTML = data.main.temp;
}
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Location"></div>
<div id="Temperature"></div>

ajax json weather auto refresh data

I am trying to make an weather auto refresh which is reloading for changes every 5 seconds. It loads perfectly first time on load but my setinterval is not working correctly. It goes of every 5 seconds but it doesnt update my menu even though changes has been made?
Here is what i got so far:
var x = document.getElementById("demo");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
var location = position.coords.latitude + "," + position.coords.longitude;
jQuery(document).ready(function(weather) {
$.ajax({
url : "https://api.wunderground.com/api/0ce1c4a981f7dd2a/geolookup/lang:AR/forecast/conditions/q/"+location+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather_html = ("<h3>Results of " + parsed_json.current_observation.display_location.city +
"</h3>" + "<p>Temperature: " + parsed_json.current_observation.temp_f + "</p>" +
"<p>Current Weather: " + parsed_json.current_observation.weather + "</p>" + "<p>Wind Gusts: " +
parsed_json.current_observation.wind_mph + "mph</p>" + '<img src="http://icons.wxug.com/logos/PNG/wundergroundLogo_black_horz.png" width="200"</img>');
$('#returned_data').html(weather_html).hide().fadeIn("slow");
$(document).ready(function() {
weather(); //Get the initial weather.
setInterval(weather, 600000); //Update the weather every 10 minutes.
});
var forecast = parsed_json['forecast']['txt_forecast']['forecastday'];
for (index in forecast) {
var newForecastString = '' + forecast[index]['title'] + ' سيكون الطقس ' + forecast[index]['fcttext_metric'];
var newForecastParagraph = $('<p/>').text(newForecastString);
$(".astro").append(newForecastParagraph);
}
}
});
});
}
It doesn't seem to be working.
$(document).ready(function() {
var weather = function() {
... your ajax function here ....
};
weather();
-- add your timer functionality here and wire it to call weather --
});
You have to declare weather as a function and then call the function. Then create your timer to repeatedly call the weather function in order to fulfill your update call.

Jquery Global Variable Scope/Wrong Values [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I have a problem with the final values assigned to global variables (success, count_error, error) in my code below. Before the outputting section if I don't include "alert( success );" all values are zero. However if I include that line then the correct values are outputted.
Why is this, is there something wrong with the variable scope ?
<html>
<head>
<script src="../jquery-1.11.0.js"></script>
<script>
var rows_all = [1,2,3,4,5,6,7,8,9,10],
success = 0,
count_error = 0,
error = [];
/////////////////////////////////////////////////////////////////////////
// In test_addresses create lat/lon [number] from coordinates [string] //
/////////////////////////////////////////////////////////////////////////
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function(data) {
//get #rows for loop function
//$.each(data.rows, function(key, val) {
//rows_all.push(val['cartodb_id']);
//});
//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function(key1, val1) {
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function(data1) {
$.each(data1.rows, function(key2, val2) {
address = val2['address'];
lat_lon = val2['coordinates'];
if (lat_lon.indexOf('?') === -1) {
lat = parseFloat( lat_lon.split(',')[0] );
lon = parseFloat( lat_lon.split(',')[1] );
$.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
success++; //number of successfully completed operations
}
else {
count_error++; //#error operations
list = {};
list["id"] = val1; //#which cartodb_id in table
list["address"] = address; //#which matching address in table
error.push(list);
}
});
});
});
alert( success );
//Ouput text
$("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");
$.each(error, function(key4, val4) {
$("#result").append("<br> " + val4["id"] + " : " + val4["address"]);
});
$.each(rows_all, function(key5, val5) {
$("#result").append("<br>" + key5);
});
});
</script>
</head>
<body>
<p id="result"></p>
</body>
</html>
It is an asynchronous request, so the alert() will fire before getting the data. So you should change the code like,
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT cartodb_id FROM test_addresses" + "&api_key=******", function (data) {
//get #rows for loop function
//$.each(data.rows, function(key, val) {
//rows_all.push(val['cartodb_id']);
//});
//loop through rows (get coordinates), manipulate + post values
$.each(rows_all, function (key1, val1) {
$.getJSON("http://******.cartodb.com/api/v2/sql?q=" + "SELECT address, coordinates FROM test_addresses WHERE cartodb_id=" + val1 + "&api_key=******", function (data1) {
$.each(data1.rows, function (key2, val2) {
address = val2['address'];
lat_lon = val2['coordinates'];
if (lat_lon.indexOf('?') === -1) {
lat = parseFloat(lat_lon.split(',')[0]);
lon = parseFloat(lat_lon.split(',')[1]);
$.post("http://******.cartodb.com/api/v2/sql?q=" + "UPDATE test_addresses SET lat=" + lat + ", lon=" + lon + "WHERE cartodb_id=" + val1 + "&api_key=******");
success++; //number of successfully completed operations
alert(success);
} else {
count_error++; //#error operations
list = {};
list["id"] = val1; //#which cartodb_id in table
list["address"] = address; //#which matching address in table
error.push(list);
}
});
//Ouput text
$("#result").html(success + " entries successfully geocoded. </br><br>There were " + count_error + " errors. <br>More pecifically at cartodb_id : address:");
$.each(error, function (key4, val4) {
$("#result").append("<br> " + val4["id"] + " : " + val4["address"]);
});
$.each(rows_all, function (key5, val5) {
$("#result").append("<br>" + key5);
});
});
});
});
You should put the code inside the scope of $.getJSON itself. So it will run only after getting the data.
Actually its not alert() doing the magic. If you put an alert, the success event will happen with in less timespan, before the user clicks ok button. Within that time all the values will be populated.

Categories