Javascript Unexpected run order - javascript

I have this jquery / javascript code below. It ask user for location permission, and then outputs a URL string with latitude appended at the end.
I put 3 console.log statemnets to highlight problem, with current outputs I get.
Expected Debug Values (in order)
1_lat =95.555555
2_lat =95.555555
3_https://fcc-weather-api.glitch.me/api/current?&lat=95.555555
Actual Debug Values: (in order)
2_
3_https://fcc-weather-api.glitch.me/api/current?&
1_lat =95.555555
var curLat ='';
var curLon ='';
var weatherAPI='';
$(document).ready(function(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
curLat = "lat=" + position.coords.latitude;
console.log("1_", curLat);
});
}
weatherAPI = getURL(curLat);
console.log("3_", weatherAPI);
});
function getURL(lat){
console.log("2_", lat);
var url = "https://fcc-weather-api.glitch.me/api/current?";
url = url + "&" + lat;
return url;
}
I must not be understanding something with how javascript is loading and how jQuery document.ready.function is affecting the results.

navigator.geolocation is async. So you have to wait for the navigator.geolocation.getCurrentPosition callback function before you can process the lat and lng
You can do something like this:
var curLat ='';
var curLon ='';
var weatherAPI='';
$(document).ready(function(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(position){
curLat = "lat=" + position.coords.latitude;
console.log("1_", curLat);
weatherAPI = getURL(curLat);
console.log("3_", weatherAPI);
});
}
});
function getURL(lat){
console.log("2_", lat);
var url = "https://fcc-weather-api.glitch.me/api/current?";
url = url + "&" + lat;
return url;
}
This will result to:
1_ lat=1.xxx
2_ lat=1.xxx
3_ https://fcc-weather-api.glitch.me/api/current?&lat=1.xxx

Related

how can i get data in API javascript?

[update]
I am using javascript to get data and display it. i created 2 functions, DATA and DISP. i then call DATA first, then call DISP...and am having trouble getting the data from fn DATA to be available globally for later. [i will use it on a weather map]
So i have tried to update with the suggestions, and although i can now force the order using ASYNCH, I still get temp=0 when accessed later, yet it displays fine insided the DATA routine.
---why isnt the global variable TEMP being changed in setup, so i can later display it by an alert with temp= what the temp is, and not temp=0
... note that it only works if i call the disp function inside of the setup, but i cant do this if i want to call multiple APIs to multiple cities
===== so here is the code===
var temp=0; //global
var longitude=0
function DATA()
{
alert(" in DATA ")
//function getWeather() {
let temperature = document.getElementById("temperature");
let description = document.getElementById("description");
let location = document.getElementById("location");
let api = "https://api.openweathermap.org/data/2.5/weather";
let apiKey = "f146799a557e8ab658304c1b30cc3cfd";
location.innerHTML = "Locating...";
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
let url =
api +
"?lat=" +
latitude +
"&lon=" +
longitude +
"&appid=" +
apiKey +
"&units=imperial";
fetch(url)
.then(response => response.json())
.then(data => {
// console.log(data);
temp = data.main.temp;
temperature.innerHTML = temp + "° F";
//DISP() // only works here
location.innerHTML =
data.name + " (" + latitude + "°, " + longitude + "°) ";
description.innerHTML = data.weather[0].main;
});
}
function error() {
location.innerHTML = "Unable to retrieve your location";
}
}
//getWeather()
//}
function DISP()
{
alert("disp temp in disp "+ temp)
tempi.innerHTML =temp;
}
async function delayedGreeting() {
DATA()
DISP()
}
delayedGreeting();
try to fix :
function displaydata(data){
...}
Also if you are working with async functions ( maybe when you try to get data from the web) make sure you use await .
await holds the process until it get's the promise back.
Also it might be helpful the add some more of the code .

How to get the values from JS in models.py file

How to get the values of JS in models.py file.
I created the model of weather information where current weather fetch from latitude and longitude. I used the api of openweathermap.org but unable to get the data of current location.
I used the following to code.
.py file
WEATHER_API_LAT_LON = "%s/weather?appid=%s&units=metric&lat={}&lon={}" % (API, APP_ID)
#api.multi
def get_weather_info(self,lat, lon):
url = WEATHER_API_LAT_LON.format(lat, lon)
print(url)
.js file
var GetLocation = function getLocation() {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
}
else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log(lat);
console.log(lon);
}
From JS get the location and merge to .py model lat and lon.
Anyone can tell how to do this.
For Odoo 10
*model.py
#api.multi
def get_weather_info(self,lat, lon):
url = WEATHER_API_LAT_LON.format(lat, lon)
print(url)
return url
*.js
// on header
var Model = require('web.Model');
// inside main function
var model = new Model('model.name').call('get_weather_info',[]).then(function(result){
console.log(result)
});
For Odoo 11
*.js
var self = this;
self._rpc({
model: 'model.name',
method: 'get_weather_info',
}, []).then(function(result){
console.log(result)
})
pass your lat and lon in the array while calling method in model.py
*.model.py
#api.multi
def get_weather_info(self,lat, lon):
url = WEATHER_API_LAT_LON.format(lat, lon)
print(url)
*.js for odoo 11
var self = this;
self._rpc({
model: 'model.name',
method: 'get_weather_info',
args: [], //Here you have to pass the arguments using keyword agrs.
}).then(function(result){
console.log(result)
})

Using a variable URL in a JSON-call, not working?

I'm trying to make a simple weather app and it seems I can't access any information using my variable for the JSON-link. Heres my code:
$(document).ready(function() {
var key = 'a91a892f1f2a1aa3f7409a78f72af675';
var locationURL = 'http://ip-api.com/json';
var longitude;
var latitude;
//Getting the geolocation from the user
$.getJSON(locationURL, function(data) {
longitude = data.lon;
latitude = data.lat;
var url = 'api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&appid=' + key;
console.log(url);
$.getJSON(url, function(data2){
console.log(data2, url);
});
});
});
But I get no return from the second JSON-call, and it seems like the variable 'url' is broken or something. What am I doing wrong or not seeing here?
You're missing protocol:
var url = '//api.openweathermap.org/data/2.5/weather?lat=' + latitude + '&lon=' + longitude + '&appid=' + key;
get: function(req, data, callback) {
data.gym_hash = this.gym_hash;
console.log(data);
$.ajax({
url: rest.server + req,
type: 'GET',
data: data,
success: function(result) {
callback(result);
}
});
}
I use this type if code and let js and jQuery do the magic of formatting the parameters into the url. Call is like this:
get(
"Path/To/Rest",
{
email: email,
password: password,
},
function(result){console.log(result);});

Geolocation locates same location multiple times

SCRIPT
/*get geo location*/
var x = document.getElementById("demo");
var y = document.getElementById("demo2");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
/* x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude; */
x.innerHTML = position.coords.latitude;
y.innerHTML = position.coords.longitude;
var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude+","+position.coords.longitude+"&sensor=false";
$.getJSON(url, function (json) {
$(".place").empty();
$(".place").css("display","block");
//console.log("JSON Data: " + json.results);
$.each(json.results, function (index, value) {
$.each(value.address_components, function (index, value) {
console.log(index + ': ' + value.long_name);
//alert(value.long_name);
localStorage.long_name = value.long_name;
console.log(localStorage.long_name);
$(".place").append(localStorage.long_name+", ");
//this line runs query to fetch users matching the places above
displayTutor(value.long_name);
});
});
});
}
//This line shows the list of places retrieved by geolocation
$(".place").append(localStorage.long_name+", ");
This is the places retrieved
See the same places returned few times like 'selangor', 'malaysia' and so forth. I think, this cause the below query return same user from the places few times.
Query
$sql="SELECT * FROM usrinfo, posts WHERE usrinfo.UUID = posts.UUID AND posts.location LIKE '%$this->place%' GROUP BY usrinfo.UUID";
It could be that, making this function call displayTutor(value.long_name); within $each loop
causes the same result fetched again and again.
The function makes ajax call to the query
function displayTutor(param){
$('#contents').empty();
$("#titleBox_content > p").text("Tutors > "+param);
$('#contents').append("<table><tr>");
var globalStore = {};
globalStore.data = [];
var data;
var getUrl;
getUrl = '/search/getLocation.php?place='+param,
$.when(
// 1st query
$.get(getUrl,function(data){globalStore.data = globalStore.data.concat(data);console.log(data)},"json")
).then(function() {
console.log(globalStore.data);
................................
.................................
Now, I need not the result same result to repeat. How to do that, please?
EDIT
I found that my query doesn't return any error as I tried in
phpmyadmin console and it doesn't return any duplicate entries. In
fact in the browser, for the first 2 seconds or so, it shows the
correct results without repeating, but after that the same results
added up. It's like the ajax call made for more than four times by the
function placed within $.each loop as above.
Can someone help me with this please?

Fetch 10000 coordinates synchronously using Google Maps

I want to fetch coordinates of 10,000 line of data using Google Maps geocoding API, and print each line to browser.
My approach is to loop each line (contain address) and pass it to Google Maps URL, then I parse those JSON data to get its lat and lng. I use jQuery.
But the problem here is it seems to run asynchronously. I have tried to use recursive but it loop without print anything. I have read to set async=false but I dont know where to place it.
Here is my current code
var x = 1;
setInterval(function(){
geturl = 'parse.php?urut='+x;
$.get(geturl, function(get){
url = get;
});
$.getJSON(url, function(data){
var lat = data.results[0].geometry.location.lat;
var lang = data.results[0].geometry.location.lng;
var nama = data.results[0].address_components[1].long_name;
$('table').append("<tr><td>"+x+"</td><td>"+lat+","+lang+"</td><td>"+nama+"</td></tr>");
});
x++;
}, 500);
Any recommendation?
This snippet of code should show you where you went wrong
function getCoords(x) {
geturl = 'parse.php?urut='+x;
$.get(geturl, function(url){
$.getJSON(url, function(data){
var lat = data.results[0].geometry.location.lat;
var lang = data.results[0].geometry.location.lng;
var nama = data.results[0].address_components[1].long_name;
$('table').append("<tr><td>"+x+"</td><td>"+lat+","+lang+"</td><td>"+nama+"</td></tr>");
});
});
}
the $.getJSON is run as part of the success function of the $.get - therefore it will get run only once the $.get is complete
I've shown this as a function, so that the value of x will be correct in the $('table').append line

Categories