Reputation: 429
I want to get weather details from this API but for some strange reason it doesn't seem to work.
It's a mashape API. https://market.mashape.com/fyhao/weather-13
Here's what I've tried,
function getWeather() {
var lat=null;
var lon=null;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
});
}
var url =
"http://simple-weather.p.mashape.com/weatherdata?lat=" +
lat +
"&lng=" +
lon;
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
$(".location").html(
"<h4>" +
data.query.results.channel.location.city +
", " +
data.query.results.channel.location.country +
"</h4>"
);
$(".weather").html(
"<h4>" + data.query.results.channel.item.condition.text + "</h4>"
);
$(".temperature").html(
"<h4>" + data.query.results.channel.item.condition.temp + "</h4>"
);
},
error: function(err) {
alert(err);
},
beforeSend: function(xhr) {
xhr.setRequestHeader(
"X-Mashape-Authorization",
"MYKEY"
);
}
});
}
$(document).ready(function() {
$(".info").addClass("animated pulse");
getWeather();
});
Any help will be appreciated.
Edit:- I am getting an alert error which says "[object Object]" due to the error function in the ajax. I did not see the error at first because I blocked pop-ups on the page.
Upvotes: 1
Views: 107
Reputation: 1432
Couple of things:
getCurrentPosition()
is asynchronous. In the way you have it set up, by the time the lat and lon variables get set to the coordinates, the $.ajax request will already have been sent with null
lat and lon variablesX-Mashape-Key
and not X-Mashape-Authorization
Here is an example:
function getWeather() {
var lat = null;
var lon = null;
if (navigator.geolocation) {
//we are putting everything inside the callback
navigator.geolocation.getCurrentPosition(function (position) {
lat = position.coords.latitude;
lon = position.coords.longitude;
var url =
"https://simple-weather.p.mashape.com/weatherdata?lat=" +
lat +
"&lng=" +
lon;
$.ajax({
url: url,
type: "GET",
success: function (data) {
console.log(data);
},
error: function (err) {
console.error('error ' + JSON.stringify(err));
},
beforeSend: function (xhr) {
xhr.setRequestHeader(
"X-Mashape-Key", "KEY"
);
}
});
});
}
}
$(document).ready(function () {
getWeather();
});
Upvotes: 4