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?
Related
[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 .
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
I'm building a project that finds the geolocation from the browser, then uses the coordinates to get data from the Dark Sky API (https://darksky.net/dev/).
I am able to get the geolocation from the browser, but am having trouble calling the JSON object once I get the geolocation. I understand that getting the geolocation is "asynchronous" and runs at the same time as my other code, and I can't seem to figure out a way around it.
Am I'm doing something wrong? It never seems to runs the: $.getJSON part.
All the #test htmls are for my reference to see where my code is going wrong. #test4 never runs, but #test3 does.
P.S. I've kept the API key hidden for my question, hence the KEY characters in the url. The myJson variable does concatenate a proper url to retrieve the JSON object.
Any help would be deeply appreciated!
var myLat;
var newMyLat;
var myLong;
var newMyLong;
var myJson;
var functionCall;
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
myLat = position.coords.latitude;
myLong = position.coords.longitude;
newMyLat = parseFloat(myLat).toFixed(4);
newMyLong = parseFloat(myLong).toFixed(4);
$("#test1").html("latitude: " + newMyLat + "<br>longitude: " + newMyLong);
myJson =
"https://api.darksky.net/forecast/KEY/" +
newMyLat +
"," +
newMyLong;
$("#test2").html(myJson);
getJsonData();
}); // end of getCurrentPosition function
} // end of navigator.geolocation function
}); // end of document.ready function
function getJsonData() {
$("#test3").html("getJsonData called");
$.getJSON(myJson, function(data) {
$("#test4").html("JSON retrieved");
}); // end of .getJSON function
} // end of getJsonData function
Answer that worked for this situation:
I just needed to add ?callback=? to the end of my JSON url, making it:
myJson = "https://api.darksky.net/forecast/ee2f66f091ed810afc3bf04adc5fa750/" + myLat + "," + myLong + "?callback=?";
Thank you for all the help!
I'm working on practicing with the openweathermap api. I have a coordinate object with keys lat & lon which are equal to a string. When I pass that coord obj into another function and try to concat those strings with the api call string they become undefined. I thought I made the scope of these variables global but it doesn't seem to be the case. Can someone tell me what is incorrect about this code
var apikey = '9575f3355ae129dc91424b5712a7695e';
var coords = {};
var accessOWM='';
function myLocation(){ navigator.geolocation.getCurrentPosition(function(position) {
coords.lat = (Math.round(position.coords.latitude*100)/100).toString();
coords.lon = (Math.round(position.coords.longitude*100)/100).toString();
});
}
function changeAccess(coordObj, key){
console.log(coordObj);
accessOWM ='http://api.openweathermap.org/data/2.5/forecast?lat='+coordObj['lat']+'&lon='+coordObj['lon']+'&APPID='+key;
}
myLocation();
console.log(coords);
changeAccess(coords, apikey);
console.log(accessOWM);
That's because getCurrentPosition method is asynchronous. This mean that getCurrentPosition's callback is not invoked at the moment of calling changeAccess function. So you have to place changeAccess call into getCurrentPosition's callback:
function myLocation() {
navigator.geolocation.getCurrentPosition(function(position) {
coords.lat = (Math.round(position.coords.latitude*100)/100).toString();
coords.lon = (Math.round(position.coords.longitude*100)/100).toString();
});
changeAccess(coords, apikey);
}
You have an issue with async code. navigator.geolocation.getCurrentPosition(successCallback) function is an asyncronious function, the successCallback will not be executed immedeately, but with some delay. That is why when you call console.log(coords) and changeAccess(coords, apiKey), the coords are not defined yet. You need to call these functions (and the last one) from inside the .getCurrentPosition() callback.
Since coords is declared in the parent scope of changeAccess, you don't need to pass coordObj into changeAccess. Have you tried:
accessOWM ='http://api.openweathermap.org/data/2.5/forecast?lat='+ coords.lat + '&lon=' + coords.lon + '&APPID='+key;
Either
var apikey = '9575f3355ae129dc91424b5712a7695e';
var accessOWM;
function round(v){ return Math.round(v*100)/100 }
function myLocation(){
navigator.geolocation.getCurrentPosition(function(position){
changeAccess(position.coords);
});
}
function changeAccess(coords){
console.log(coordObj);
accessOWM ='http://api.openweathermap.org/data/2.5/forecast?lat=' + round(coords.latitude) + '&lon=' + round(coords.longitude) + '&APPID=' + apikey;
console.log(accessOWM);
}
myLocation();
Or
var apikey = '9575f3355ae129dc91424b5712a7695e';
var accessOWM = myLocation().then(changeAccess);
accessOWM.then(function(v){
console.log(v);
})
function round(v){ return Math.round(v*100)/100 }
function myLocation(){
return new Promise(function(resolve){
navigator.geolocation.getCurrentPosition(function(position){
resolve(position.coords);
});
});
}
function changeAccess(coords){
return 'http://api.openweathermap.org/data/2.5/forecast?lat=' + round(coords.latitude) + '&lon=' + round(coords.longitude) + '&APPID=' + apikey;
}
I'm using the following code:
function eventListenerTest(event) {
if (document.getElementById('gem_cvo_select_list')) {
var address;
$.getJSON(url, function (data) {
address = data.rows[0];
alert("This gets executed afterwards");
});
alert("This gets executed first");
event.infoWindowHtml = "<b>Address: </b>" + address;
}
}
Problem is the $.getJSON function gets executed after the 'address' variable is used in the infoWindow. Modified the code like this:
function eventListenerTest(event) {
if (document.getElementById('gem_cvo_select_list')) {
var address;
$.getJSON(url, function (data) {
address = data.rows[0];
event.infoWindowHtml = "<b>Address: </b>" + address;
});
}
}
The 'event' object doesn't seem to be accessible this way (nothing is displayed in the Google Maps infoWindow). I figured I should be able to pass 'event' to the function inside the JSON but I have no idea how to accomplish this.
Try this:
function eventListenerTest(event, callback) {
if (document.getElementById('gem_cvo_select_list')) {
var address;
$.getJSON(url, function (data) {
address = data.rows[0];
event.infoWindowHtml = "<b>Address: </b>" + address;
callback();
});
}
}
Then:
eventListenerTest(event, function(){
// you will use updated event object here
});
You should use $.proxy method to make sure that the callback function that gets executed keeps the context of the function creating the Ajax call.
Updated Javascript:
function eventListenerTest(event) {
if (document.getElementById('gem_cvo_select_list')) {
var address;
$.getJSON(url, $.proxy(function (data) {
address = data.rows[0];
event.infoWindowHtml = "<b>Address: </b>" + address;
},this));
}
}
More information: http://api.jquery.com/jQuery.proxy/