How to get JSON after geolocation in JavaScript/jQuery? - javascript

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!

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 automate a geolocation based Json

I am a beginner and I have a function to get the link based on your location.
Here is the function:
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "http://api.openweathermap.org/data/2.5/weather?lat=" + position.coords.latitude + "&lon=" +
position.coords.longitude + "&units=metric&APPID=3d1523ca3f27251ddf055b1b26ed347f"
}
</script>
now I am trying to get this link into a get.Json so that the website will automatically get information about the weather in your area. The problem is that I can't get it to work. can someone help me on how to get the link into a get.Json automatically.
To get data from some web api endpoint you need to use some ajax request api. Native ones are XMLHTTPRequest, fetch().
There is also jQuery.ajax and its aliases $.post,$.get,$.getJSON etc
So just use the api that you are comfortable with and add it to your showPosition function. When the respective api's promise, or event callback is triggered used the passed data to display your information:
function showPosition(position) {
let apiUrl = "http://api.openweathermap.org/data/2.5/weather?lat=" +
position.coords.latitude +
"&lon=" + position.coords.longitude +
"&units=metric&APPID=3d1523ca3f27251ddf055b1b26ed347f";
//using fetch() api
fetch(apiUrl).then(response=>response.json()).then(data=>{
//use the returned data however you like
//for instance show temperature
x.innerHTML = data.main.temp;
});
//using XMLHttpRequest
let req = new XMLHttpRequest();
req.open("get",apiUrl);
req.addEventListener('load',function(data){
//use the returned data however you like
});
//using a library like jQuery
jQuery.getJSON(apiUrl).then(function(data){
//use the returned data however you like
});
}
Read up on asynchronous operations and avoid pitfalls like these:
How do I return the response from an asynchronous call?
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Scope issue between jQuery request and d3.js

I'm struggling with a scope question.
Basically, I am making an API request with jQuery's $.getJSON()
Then I intend to use the result to draw a graph with D3.js.
var url = 'http://query.yahooapis.com/v1/public/yql';
var startDate = '2013-09-06';
var endDate = '2014-03-06';
var req = encodeURIComponent('select * from yahoo.finance.historicaldata where symbol in ("YHOO") and startDate = "' + startDate + '" and endDate = "' + endDate + '"');
var dd = $.getJSON(url, 'q=' + req + "&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json", function(data) {
console.log(data);
console.log(data.query.results.quote[0]);
});
console.log("lol"); //works fine
console.log(data); //doesn't work
console.log(dd); //works
console.log(dd.data); //doesn't work
I am very confused.
How can I use the results of my query in d3.js?
Thank you very much
$.getJSON is asynchronous. This means that when you execute the code, it sends off the request. Then the code below it is executed -- nothing has come back yet. When the request returns, the handler function is called with the data. This is where you need to do everything you want to do with the data.
$.getJSON(url, function(data) {
// make graph
});
Note that D3 provides its own function for retrieving JSON:
d3.json(url, function(error, data) {
// make graph
});

Retrieving JSON throws error: Unexpected token :

I'm retrieving the elevation data from the Google Maps API by AJAX.
I'm getting the data back I want as if I look at the console in Chrome I can see a 200 status code and can see the data in the response tab. But is throws up 'Uncaught SyntaxError: Unexpected token :' so I can't display anything from the JSON file.
This is my code:
var theURL = 'http://maps.googleapis.com/maps/api/elevation/json?locations=' + longitude + ',' + latitude + '&sensor=false&callback=?';
$.ajax({
url: theURL,
type: 'get',
dataType: 'json',
cache: false,
crossDomain: true,
success: function (data) {
var theData = $.parseJSON(data);
console.log(theData);
}
});
The live code is here: http://map.colouringcode.com/
All help is greatly appreciated.
The Google Maps API does not support direct JSONP requests.
Instead, you need to use the Javascript API.
Realizing this question is well outdated, I hope that this might be able to help someone in the future. This was my first encounter with javascript and especially all this JSON stuff and therefore caused a lot of hitting my head off the desk trying to figure out what I was doing wrong.
Here is my solution that retrieves the clients location (in lat and lng) and then uses the google geocoding api to determine their location in "human readable" format.
function currentLocation() {
navigator.geolocation.getCurrentPosition(foundLocation, errorLocation);
function foundLocation(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
//This is where the geocoding starts
var locationURL= "http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ lat + "," + lng + "&sensor=false&callback=myLocation"
//This line allows us to get the return object in a JSON
//instead of a JSONP object and therefore solving our problem
$.getJSON(locationURL, myLocation);
}
function errorLocation() {
alert("Error finding your location.");
}
}
function myLocation(locationReturned) {
var town = locationReturned.results[0].address_components[1].short_name;
var state = locationReturned.results[0].address_components[4].short_name;
console.log(town, state);
}

jQuery getJSON never enters its callback function

I've been sitting with this for hours now, and I cant understand why.
q is working. The URL does give me a proper JSON-response. It shows up as objects and arrays and whatnot under the JSON tab under the Net-tab in Firebug and all is fine. I've also tried with other URLs that i know work. Same thing happens.
I have another function elsewhere in my tiny app, wihch works fine, and is pretty much exactly the same thing, just another API and is called from elsewhere. Works fine, and the data variable is filled when it enters the getJSON-function. Here, data never gets filled with anything.
I've had breakpoints on every single line in Firebug, with no result. Nothing happens. It simply reaches the getJSON-line, and then skips to the debugger-statement after the function.
var usedTagCount = 10;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
for(var i = 0; i < usedTagCount; i++) {
tagString += query[i].key + ",";
}
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
debugger; /* It never gets here! */
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
debugger;
return flickrImageData;
}
Example of request URL (q):
http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=20&jsoncallback=?&tags=london,senior,iphone,royal,year,security,project,records,online,after,
I do wonder, since JSONView (the firefox plugin) cannot format it properly, that it isn't really JSON that is returned - the mime-type is text/html. Firebug, however, interprets it as JSON (as i stated above). And all the tag words come from another part of the app.
I think you might need to remove the
nojsoncallback=1
from your searchAPI string.
Flickr uses JSONP to enable cross domain calls. This method requires the JSON to be wrapped in a json callback, the nojsoncallback=1 parameter removes this wrapping.
EDIT: Apparently it works with nojsoncallback=1, I got this piece of code to work for me. What jQuery version are you using? JSONP is only available from 1.2 and up.
This works for me (slight modifications):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
var usedTagCount = 1;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
tagString = query;
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
}
search("cat");
</script>
When I try the url: http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=10&tags=mongo
it returns data, as it should -
try to change the getJSON to an $.ajax() and define a function jsonFlickrApi (data)
with the code you have in you callback function.
If that don't work - please post code to at jsbin.com <- so we can try it live - so much easier to debug.

Categories