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
Related
I am trying get current location with address by using Cordova geolocation plugin . but i am getting below error message.
{error_message: "You must use an API key to authenticate each reque…, please refer to http://g.co/dev/maps-no-account", results: Array(0), status: "REQUEST_DENIED"}
error_message: "You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account"
results: []
status: "REQUEST_DENIED"
for getting current location. below code i am using please correct my code
$scope.init = function () {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
if (navigator.connection.type == Connection.NONE) {
} else {
}
var networkConnection = navigator.connection.type;
if (networkConnection != null) {
navigator.geolocation.getCurrentPosition(success, error);
}
else {
alert('Please check your network connection and try again.');
}
}
function success(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
getDetails(latitude, longitude);
}
function error(error) {
alert('Please check your network connection and try again.');
}
function getDetails(latitude, longitude) {
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&sensor=false";
$.getJSON(url, function (data) {
console.log(data);
});
}
Please correct my code i expected out put current location with address. Thanks for advance.
You must use an API key
When you signed up for the maps platform, you should have gotten an access key, which you need to pass with every request to authenticate.
Now, as far as i can see, you don't have that token on your URL parameters. ( You may need to send it with the request headers, check the API docs on how it expects it)
EDIT:
This is the format:
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap
Try this:
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "?key= "+"ADD YOUR KEY HERE" + "&sensor=false";
Also, try using template strings rather than having 10s of + in your string
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I'm building a weather App using reactjs and the geolocation(navigator) api with the darksky weather api. I got the longitude and latitude displaying correctly, but when I try to retrieve the data I get a {code: 400, error: "The given location (or time) is invalid."}. However, if i manually put the address into the browser I get the proper JSON returned.
Example URL request: https://api.darksky.net/forecast/{api_secret_key}/37.4498,-77.3047
Looking at the headers in the console it doesn't even appear that the requested URL contains the longitude and latitude I'm passing in. Might it be that the weather API call is being executed before I get the latitude and longitude?
Request URL per console: https://api.darksky.net/forecast/{api_secret_key}/,
getWeather = async (e) => { //Get weather data
let latitude = '';
let longitude = '';
e.preventDefault(); //prevent page reload behaviour
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
latitude = position.coords.latitude.toFixed(4); //save lat and lon from above API call
longitude = position.coords.longitude.toFixed(4);
console.log("Latitude: " + latitude + ", Longitude: " + longitude);
});
} else {
console.log("Geolocation not available");
}
//Pass the lattitude and longitude values from the location API call to the weather API
const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/${latitude},${longitude}`);
const weather_data = await weather_api_call.json(); //retrieve weather API data
console.log(weather_data); //print weather API data to console
}
Answer: Ended up moving the fetch and logging of the weather API data into the getCurrentPosition function
getWeather = (e) => {
e.preventDefault(); //prevent page reload behaviour
if ("geolocation" in navigator) { //if the users allows geolocation to be active
navigator.geolocation.getCurrentPosition(async (position) => { //access naviagotr API & get the users current lat and lon
let latitude = position.coords.latitude.toFixed(4); //save lat and lon from above API call
let longitude = position.coords.longitude.toFixed(4);
console.log("Latitude: " + latitude + " Longitude: " + longitude); //check lat and lon
//Pass the lattitude and longitude values from the location API call to the weather API
const weather_api_call = await fetch(`https://api.darksky.net/forecast/${api_secret_key}/`+latitude+`,`+longitude); //run API call after when lat and lon data is gotten
const weather_data = await weather_api_call.json(); //retrieve weather API data after the call is executed with the lat and lon
console.log(weather_data); //print weather API data to console
});
} else {
console.log("Geolocation not available"); //Log if user blocks location in browser
}
}
navigator.geolocation.getCurrentPosition is an async call where you're setting the values of latitude and longitude in the supplied callback. However the getWeather function just keeps executing along and calls the fetch with the original latitude and longitude values which are defined as empty strings.
If you move your fetch calls into the callback of navigator.geolocation.getCurrentPosition where you are sure that latitude and longitude are defined it should be fine.
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 am going to make a web app that show local weather using openweathermap api.
When I click the button, an IP API was called to get the co-ordinate of my location(longitude and latitude). These information then was used with API key (I registered in the website openweathermap.org) to create URL to call weather info according to the APIdocs, then change the HTML element with the data got from the server. I doing this on codepen. I tried to do the simplest one but it doesn't work.
<h1>weather forcast</h1>
<button id="btn">view</button>
<p id ="test">change me</p>
<p id ="place">place</p>
<p id ="temp">temperature</p>
<p id ="description">description</p>
var getLocation = function(data) {
var lat = data.lat;
var lon = data.lon;
var apiKey = "[APIKEY]";
};
var url = 'http://api.openweathermap.org/data/2.5/weather?' + 'lat=' + lat + '&lon=' + lon + '&appid=' + apiKey;
//call back function to extract weather info.
var getWeather = function(data) {
var temp = data.main.temp;
var description = data.weather[0].description;
var place = data.name;
};
$(document).ready(function() {
$("#btn").click(function() {
$.getJSON('http://ip-api.com/json', getLocation, 'jsonp')
$.getJSON(url, getWeather, 'jsonp');
$("#test").text("I AM CHANGED. THANKS!")
$("#temp").text(temp)
$("#description").text(description)
$("#place").text(place)
})
})
You have several issues. The first is that the $.getJSON calls are asynchronous, so the text() of the elements will be changed before any request completes. You need to place all code dependant on the values returned from the request in the callback functions.
Secondly you have issues with variable scope where you're defining your variables inside the function and then attempting to use them outside where they will be undefined.
With that said, you need to re-arrange your logic to something like this:
var getWeather = function(data) {
$.getJSON('http://api.openweathermap.org/data/2.5/weather', {
lat: data.lat,
lon: data.lon,
appid: "[APIKEY HERE]"
}, showWeather, 'jsonp');
};
var showWeather = function(data) {
$("#test").text("I AM CHANGED. THANKS!")
$("#temp").text(data.main.temp)
$("#description").text(data.weather[0].description)
$("#place").text(data.name)
};
$(document).ready(function() {
$("#btn").click(function() {
$.getJSON('http://ip-api.com/json', getWeather)
})
})
Note that the function calls are chained from the event (ie the click makes the location AJAX request, which calls getWeather which then calls showWeather. Also note how the variables are now local and used within their own function scope.
Finally, check that you're using the correct data formats for the AJAX requests. ip-api.com/json is returning JSON, not JSONP.
You can get data about the location with use third-party API. for example:http://ip-api.com/.
You get your location weather data from OpenWeatherMap service using the ip-api. its help you to get visitor location weather.
var getIP = 'http://ip-api.com/json/';
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'
$.getJSON(getIP).done(function(location) {
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
units: 'metric',
APPID: 'Your-Openweather-Apikey'
}).done(function(weather) {
$('#weather').append(weather.main.temp);
console.log(weather);
})
})
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to learn Node.js
I am having trouble creating my own call back on a function. It seems like such a simple thing but I don't quite understand how to do it.
The function is passed an address (example: "1234 will ln, co") which uses google's geolocate json api to return the full address, latitude and longitude in an array.
Here is my code:
//require secure http module
var https = require("https");
//My google API key
var googleApiKey = "my_private_api_key";
//error function
function printError(error) {
console.error(error.message);
}
function locate(address) {
//accept an address as an argument to geolocate
//replace spaces in the address string with + charectors to make string browser compatiable
address = address.split(' ').join('+');
//var geolocate is the url to get our json object from google's geolocate api
var geolocate = "https://maps.googleapis.com/maps/api/geocode/json?key=";
geolocate += googleApiKey + "&address=" + address;
var reqeust = https.get(geolocate, function (response){
//create empty variable to store response stream
var responsestream = "";
response.on('data', function (chunk){
responsestream += chunk;
}); //end response on data
response.on('end', function (){
if (response.statusCode === 200){
try {
var location = JSON.parse(responsestream);
var fullLocation = {
"address" : location.results[0].formatted_address,
"cord" : location.results[0].geometry.location.lat + "," + location.results[0].geometry.location.lng
};
return fullLocation;
} catch(error) {
printError(error);
}
} else {
printError({ message: "There was an error with Google's Geolocate. Please contact system administrator"});
}
}); //end response on end
}); //end https get request
} //end locate function
So when I try to execute my function
var testing = locate("7678 old spec rd");
console.dir(testing);
The console logs undefined because its not waiting for the return from locate (or at least I am guessing this is the problem).
How do i create a call back so when the locate function returns my array, it runs the console.dir on the array it returned.
Thanks! I hope my question makes sense, im self taught so my tech jargon is horrible.
You need to pass in the callback function to your method - so the callback might look something like this
function logResult(fullLocation){
console.log(fullLocation)
}
You would pass this in to your locate method along with the input:
// note: no parentheses, you're passing a reference to the method itself,
// not executing the method
locate("1234 will ln, co",logResult)
You can also do this inline - much like the response object you're already dealing with:
locate("1234 will ln, co",function(fullLocation){
// do something useful here
})
Now for the bit inside your method, instead of trying to return the result you just call the callback with the result:
function locate(address, callback) {
......
response.on('end', function (){
if (response.statusCode === 200){
try {
var location = JSON.parse(responsestream);
var fullLocation = {
"address" : location.results[0].formatted_address,
"cord" : location.results[0].geometry.location.lat + "," + location.results[0].geometry.location.lng
};
callback(fullLocation); // <-- here!!!
} catch(error) {
printError(error);
}
} else {
printError({ message: "There was an error with Google's Geolocate. Please contact system administrator"});
}
}); //end response on end
.....
}