Javascript jQuery function does not define variables - javascript

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;
});
}```

Related

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.

Leaflet JS with loop in JavaScript

I'm trying to create a loop to add multiple markers to an Leaflet map. One marker works, but when I try to do this with a loop, the markers don't work. I receive the data for the markers from a google spreadsheet.
$(document).ready(function() {
console.log("ready!");
// ID of the Google Spreadsheet
var spreadsheetID = "spreadsheetID";
// Make sure it is public or set to Anyone with link can view
var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/1/public/values?alt=json";
$.getJSON(url, function(data) {
var entry = data.feed.entry;
var amount = entry.lenght;
var i;
for (i = 0; i <= amount; i++) {
var lat = data.feed.entry[i]['gsx$lat']['$t'];
var lon = data.feed.entry[i]['gsx$lon']['$t'];
var name = data.feed.entry[i]['gsx$name']['$t'];
var to = data.feed.entry[i]['gsx$to']['$t'];
var time = data.feed.entry[i]['gsx$time']['$t'];
var tel = data.feed.entry[i]['gsx$tel']['$t'];
var marker = L.marker([lon, lat]).addTo(mymap);
marker.bindPopup('<b>Name:</b> ' + name + '<br><b>To:</b> ' + to + '<br><b>Time:</b> ' + time + '<br><b> Tel:</b> ' + tel);
}
})
});
Your code with typo and LatLng problem fixed:
$(document).ready(function() {
console.log("ready!");
// ID of the Google Spreadsheet
var spreadsheetID = "spreadsheetID";
// Make sure it is public or set to Anyone with link can view
var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID + "/1/public/values?alt=json";
$.getJSON(url, function(data) {
var entry = data.feed.entry;
var amount = entry.length;
var i;
for (i = 0; i < amount; i++) {
var lat = data.feed.entry[i]['gsx$lat']['$t'];
var lon = data.feed.entry[i]['gsx$lon']['$t'];
var name = data.feed.entry[i]['gsx$name']['$t'];
var to = data.feed.entry[i]['gsx$to']['$t'];
var time = data.feed.entry[i]['gsx$time']['$t'];
var tel = data.feed.entry[i]['gsx$tel']['$t'];
var marker = L.marker([lat, lon]).addTo(mymap);
marker.bindPopup('<b>Name:</b> ' + name + '<br><b>To:</b> ' + to + '<br><b>Time:</b> ' + time + '<br><b> Tel:</b> ' + tel);
}
})
});

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>

Maximum call stack size exceeded with using google maps and jQuery

Do you know why I get Maximum call stack size exceeded if I insert a code inside a function and execute it.
$(function() {
function loadContent() {
$.getJSON("js/data.json").done(function(data) {
var content = '';
$.each(data, function(i, item) {
content += '<div class="item" id="' + item.id + '" data-lat="' + item.latitude + '" data-lng="' + item.longitude + '" style="background-image: url(img/' + item.photo + ');"><div class="item__wrapper"><h2 class="item__title">' + item.title + '</h2><p class="item__content">' + item.description + '</p><span class="lat"><i class="fa fa-location-arrow"></i> ' + item.latitude + ' N, </span><span class="long">' + item.longitude + ' E</span></div></div>';
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker({
position: latLng
});
marker.setMap(map);
});
$('#sidebar').html(content);
$('.item').on("click", function() {
$(this).toggleClass("item--expanded").siblings().removeClass("item--expanded");
});
}).fail(function() {
var content = '<p>Błąd wczytywania danych!</p>';
$('#sidebar').html(content);
});
}
loadContent();
});
If I don't use function loadContent() It works fine. I've read it Maximum call stack size exceeded error but I don't execute the loop inside loop.
Edit: The problem is cause by this code:
<script>
var placeList = document.getElementById("sidebar");
placeList.addEventListener("click", getPlace, false);
function getPlace(ev) {
if (ev.target !== ev.currentTarget) {
clickedItem = ev.target.id;
var getItem = document.getElementById(clickedItem);
var lat = getItem.dataset.lat;
var lng = getItem.dataset.lng;
}
var center = new google.maps.LatLng(lat, lng);
map.panTo(center);
map.setZoom(13);
}
</script>
But still don't know why!

Javascript Geolocation API

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();
});

Categories