how can i get data in API javascript? - 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 .

Related

Data duplication on click on the WMS

When the user click for the first time on the map, he can see the related information. But if he click again, the informations are duplicated as you can see on the image below.
I expect that the old information is substitute with the newest.
For handle this request I've developed the function below:
function getElementInfo(elementID, layerName, layerTitle){
map.on('singleclick', function (event) {
var viewResolution = view.getResolution();
var coordinates = event.coordinate;
var epsg = 'EPSG:3857';
var params = {
'INFO_FORMAT': 'application/json'
};
var url = layerName.getSource().getFeatureInfoUrl(
coordinates,
viewResolution,
epsg,
params,
);
async function getFeatureProperties() {
try {
var response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error!\n Status: ${response.status}\n Type: ${response.type}\n URL: ${response.url}`);
} else {
var data = await response.text();
var json = JSON.parse(data).features[0].properties;
var tableHeadContents = '<thead>'
+ '</thead>';
var tableHead = $(tableHeadContents).attr("id","thead");
$("#"+elementID).append(tableHead);
var tableBodyContents = '<tbody></tbody>';
var tableBody = $(tableBodyContents).attr("id","tbody");
$("#"+elementID).append(tableBody);
for (items in json) {
key = items;
value = json[items];
tableRow = '<tr><td class="td-head">' + key + '</td><td class="td-body">' + value + '</td></tr>';
$("tbody").append(tableRow);
}
}
} catch (e) {
console.log(e);
}
}
getFeatureProperties();
});
};
I haven't strong skills with Javascript and probably there is an error here but I can't see it.
I call the function simply adding it after a TileWMS:
getElementInfo('onclickinfo35', wms35, 'NDVI Campania 20150807');
And the informations appears inside a simple table:
<table id="onclickinfo35"></table>
The reason why you are getting more and more values/rows in your table for every click, is because you don't clear the table before adding data.
You need to call $("#"+elementID).html(); before $("#"+elementID).append(tableHead);

How to get JSON after geolocation in JavaScript/jQuery?

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!

AngularJS and $http get JSON - data is not defined

Hi I am trying to retrieve some data from webservice using AngularJS $http get.
I have the following code snippet:
In the servicesjs:
.factory('BoothDesignatedCoordsService', ['$http', function ($http) {
var factory = {};
factory.getBoothDesignatedCoords = function (strBoothName, intFloorPlanID) {
var sendToWS;
var boothDesignatedCoords
var JSONObj = {
BoothName: strBoothName,
FloorPlanID: intFloorPlanID
};
sendToWS = JSON.stringify(JSONObj)
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords?objJSONRequest=' + sendToWS;
return $http.get(urlBase)
}
return factory;
}])
In the controllerjs:
var boothDesignatedCoords = BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3).success(function (response, data, status) {
console.log("successfully send booth name and floor plan id to ws");
console.log("data " + data + " , status : " + status);
console.log("data " + data);
boothDesignatedCoords = data;
for (var c = 0; c < boothDesignatedCoords.length; c += 2) {
}
The $http get is successful as I am able to print "successfully send booth name and floor plan id to ws" in the browser console log.
When I tried to print console.log("data " + data), it gives me some values of an integer array. That is exactly what I want. But in the controller I tried to assign data to the variable boothDesignatedCoords, the program does not run the for loop. Am I missing some code?
EDIT:
I tried to trace the code ( trace the variable called "data" in the controllerjs) and it says "data is not defined"
You appear to be confused about the methods available on the $http promise and their arguments. Try this
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
var data = response.data
var status = response.status
console.log('data', data) // note, no string concatenation
// and so on...
})
FYI, the success and error methods have been deprecated for some time and removed from v1.6.0 onwards. Don't use them.
I also highly recommend passing query parameters via the params config object
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords'
return $http.get(urlBase, {
params: { objJSONRequest: sendToWS }
})
This will ensure the key and value are correctly encoded.

String value becomes undefined when trying to concat another string

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

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?

Categories