I'm trying to make a page that will use the openweathermap api to display the user's city and local temperature, unfortunately it doesn't seem to be processing the JSON api and is doing nothing. My code is fine as far as I can tell so I don't understand what's wrong.
Here's the jsfiddle link and javscript code: https://jsfiddle.net/qo2h1L9e/2/
$(document).ready(function() {
var data;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log(lat);
console.log(lon);
console.log("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886");
$.getJSON("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886", function(json) {
data = json;
console.log(data.name);
$("#city").text(data.name);
});
});
}
});
I had a similar issue when coding this. Assuming you're on FCC?
Anyways, try adding &callback=? to the api URL. You may need to get the data as JSONP rather than JSON.
Also, you don't need to define data. You could access the object directly through the json parameter.
I have done it jQuery try this code
$(document).ready(function() {
var data;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
console.log(lat);
console.log(lon);
console.log("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886");
// $.getJSON("api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&APPID=4907e373098f091c293b36b92d8f0886", function(json) {
// data = json;
// console.log(data.name);
// $("#city").text(data.name);
// });
var url = 'http://api.openweathermap.org/data/2.5/weather';
var params = {};
params.lat = lat;
params.lon = lon;
params.APPID = "4907e373098f091c293b36b92d8f0886";
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
data: params,
success: function (res) {
console.log(res);
},
error: function (res) {
}
});
}
);
}
});
The problem is in json.For cross domain use jsonp.
Related
One of my recent projects is to successfully get the temperature to convert from Fahrenheit to Celsius. However, I have run into a problem that gives me an undefined value when I click my button. Should I be referring to the temperature value that I have requested from my API? I believe that my conversion within my weather function isn't running when I call it.
Here's my codepen.
https://codepen.io/baquino1994/pen/qXjXOM?editors=0010
HTML
<span id="temp"></span>
<button id="tempunit">F</button>
JS
function weather(){
function success(position){
var latitude = position.coords.latitude;
var longitude= position.coords.longitude;
// location.innerHTML = "Latitude:" + latitude+"°"+ "Longitude: " + longitude+'°';
var theUrl = url +apiKey + "/"+ latitude+","+ longitude +"?callback=?";
$.getJSON(theUrl, function(data){
$("#temp").html(data.currently.temperature)
$("#minutely").html(data.minutely.summary)
// currentTempInFahrenheit = Math.round(data.html.currently.temperature * 10) /
$("#tempunit").text(tempUnit);
$.ajax({
url:'https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=AIzaSyBpiTf5uzEtJsKXReoOKXYw4RO0ayT2Opc', dataType: 'json',
success: function(results){
$("#city").text(results.results[3].address_components[4].long_name)
$("#country").text(results.results[0].address_components[5].long_name)
}
}
)}
);
}
var location = document.getElementById("location");
var apiKey = "3827754c14ed9dd9c84afdc4fc05a1b3";
var url = "https://api.darksky.net/forecast/";
navigator.geolocation.getCurrentPosition(success);
// location.innerHTML = "Locating...";
}
$(document).ready(function(){
weather();
});
var tempUnit = "F";
var currentTempInFahrenheit;
$("#tempunit").click(function(){
var currentTempUnit = $("#tempunit").text();
var newTempUnit = currentTempUnit == "F" ? "C" : "F";
$('#tempunit').text(newTempUnit);
if(newTempUnit == "F"){
var celTemp = Math.round(parseInt($('#temp').text())*5/9 - 32);
$("#temp").text(celTemp + " " + String.fromCharcode(176));
}
else{
$("#temp").text(currentTempInFahrenheit + " " + String.fromCharCode(176));
}
})
try this, my browser blocked geolocation, when i mocked the location i was able to get the codepen to work.
var location = document.getElementById("location");
var apiKey = "3827754c14ed9dd9c84afdc4fc05a1b3";
var url = "https://api.darksky.net/forecast/";
// navigator.geolocation.getCurrentPosition(success);
var position = { coords: { latitude: 32, longitude: -96 } };
success(position);
I'm trying to define the search city based off the user's longitude and latitude which I'm accessing through .geolocation
When adding the long and lat to my url I get this error
cod : "400" message : "-104.9435462 is not a float"
getLocation();
//Find Location of Device
function getLocation(callback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getData);
}
}
//Get/set Variables
function getData(position) {
var longitude = position.coords.longitude;
var latitude = position.coords.latitude;
var altitude = position.coords.altitude;
var heading = position.coords.heading;
var speed = position.coords.speed;
var date = position.timestamp;
getWeather(longitude, latitude);
console.log(longitude);
console.log(latitude);
}
//Call OpenWeatherAPI
function getWeather(x, y) {
const apiKey = '';
var url = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + x + '&lon=' + y + '&APPID=280e605c456f0ba78a519edde1a641d3';
$.ajax({
url: url,
success: function(result) {
}
});
}; //END getWeather()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Late answer, but hopefully this will save others time. The error message is misleading.
The error occurs because the longitude, which has a range of -180 to 180, was placed in the latitude, which has a range of -90 to 90.
In the code, getWeather() call was made like this:
getWeather(longitude, latitude);
However, notice that the latitude and longitude (x, y) are ordered (latitude, longitude) in the function:
function getWeather(x, y) {
const apiKey = '';
var url = 'http://api.openweathermap.org/data/2.5/forecast?lat=' + x + '&lon=' + y + '&APPID= removed id';
// additional code
};
Changing the call should resolve the problem:
getWeather(latitude, longitude);
this is continue for Q before Orginal q
i'm trying to figure out how to pass Id to link (E>G http://localhost:1914/en/Events/Index/22) .
i was suggested to pass it view json results buti cantpass it back to my script file what i need is after user submit to pass the Id to a url and display the new posted item. (EG MyDomain/GolblizionCode/Controller/View/Id) .with what i got so far i have undefined instead if Id .(http://localhost:1914/EN/Events/Indexundefined )
Code: GetAddres.Js `
function GetLocation() {
var geocoder = new window.google.maps.Geocoder();
var street = document.getElementById('txtAddress').value;
var city = document.getElementById('txtCity').value;
var address = city + street;
console.log(address);
var labelLat = document.getElementById('Latitude');
var labellong = document.getElementById('longitude');
geocoder.geocode({ 'address': address },
function(results, status) {
if (status == window.google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
console.log("Latitude: " + latitude + "\nLongitude: " + longitude); //Ok.
labelLat.value = latitude; //Ok.
labellong.value = longitude;
var form = $('#RestoForm')[0];
var formData = new FormData(form);
var getUrl = window.location;
var baseUrl = getUrl.protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
$.ajax({
url: 'Create',
type: 'POST',
contentType: false,
processData: false,
data: formData,
datatype: "JSON",
success: function(data) {
$('#RestoForm').html(data);
var id = data.id;
console.log(id);
window.location.href = baseUrl + '/Events/Index' + id;
console.log(baseUrl + '/Events/Index' + id);
}
});
error: function e(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
}
});
};`
controller:`
public ActionResult Create()
{
var viewModel = new LectureFormViewModel
{
Genres = _context.Genres.ToList(),
};
return View("Gigform", viewModel);
}
[Authorize, HttpPost]
public JsonResult Create(LectureFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
//return View("Gigform", viewModel);
}
var lectureGig = new LectureGig
{
//Parmeters
};
_context.LectureGigs.Add(lectureGig);
_context.SaveChanges();
return Json(new {Id = lectureGig.Id});
}
}`
Thanks in advance
Try to add the allow get on the Json Response
return Json(new {Id = lectureGig.Id}, JsonRequestBehavior.AllowGet);
Hope this helps
return Json(new {Id = lectureGig.Id}, JsonRequestBehavior.AllowGet);
or you can use ViewBag
C#
ViewBag.MyIdBag = lectureGig.Id;
Razor
#ViewBag.MyIdBag
I am making a basic web-based weather app, which detects the current weather conditions in the user's location. My current code so far does work, but is missing an important feature - I want the background of the web page to change according to the user's location and weather conditions. For instance - if a user is in New York and the weather is sunny, I would like to display any New York based popular image(ex: Times Square) along with sunny skies as the body background. I've searched several APIs but haven't found any that meets my needs.
In my current code, I'm using IPInfo.io to get the user's location and OpenWeatherMap to get the weather conditions.
This pen has my code (NOTE - code for units hasn't been added yet), and here's the JS bit -
var lat = 0.0,
lon = 0.0;
var testURL = 'http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=2de143494c0b295cca9337e1e96b00e0';
var myURL = 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid="ae0acb60e8db4952e081c2fb470a1b23"';
var city = '',
state = '',
country = '',
postal = 0;
//if (navigator.geolocation) {
// /* geolocation is available */
// navigator.geolocation.getCurrentPosition(function (position) {
// lat = position.coords.latitude;
// lon = position.coords.longitude;
// console.log("Latitude = " + lat);
// console.log("Longitude = " + lon);
//
// display(position.coords.latitude, position.coords.longitude);
// });
//
//} else {
// /* geolocation IS NOT available */
// $("#jumbotron").html("geolocation not available");
//
//}
//get co-ordinates using ipinfo.io
$.getJSON('http://ipinfo.io', function (data) {
console.log(data);
var loc = data.loc;
lat = loc.split(",")[0];
lon = loc.split(",")[1];
display(lat, lon);
city = data.city;
state = data.region;
country = data.country;
postal = parseInt(data.postal, 10);
})
function display(x, y) {
$("#pos1").html("<b>" + x + "</b>");
$("#pos2").html("<b>" + y + "</b>");
}
//function to calculate wind direction from degrees
function degToCompass(num) {
//num = parseInt(num, 10);
console.log("Inside degtocompass = " + num);
var val = Math.floor((num / 22.5) + 0.5);
var arr = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"];
return arr[(val % 16)];
}
//function to return current temperature
function convertTemp(currTemp) {
//get celsius from kelvin
return Math.round(currTemp - 273.15);
}
$("button").click(function () {
console.log("In Latitude = " + lat);
console.log("In Longitude = " + lon);
//prepare api call
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?lat=' + lat + '&lon=' + lon + '&appid=ae0acb60e8db4952e081c2fb470a1b23',
//url: testURL,
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function (data) {
console.log(data);
//---------get the clipart---------------
var picLink = 'http://openweathermap.org/img/w/';
var picName = data.weather[0].icon;
picLink += picName + ".png";
$("#picture").empty().append('<img src="' + picLink + '">');
//----------get the temperature-----------
var curTemp = convertTemp(data.main.temp);
console.log("Current temp = " + curTemp);
//$("#temp").empty().append("<b>" + curTemp + "</b>");
$("#picture").append("<b>" + curTemp + "</b>");
//----------get the place----------------------
var area = city + ", " + state + ", " + country;
$("#area").empty().append("<b>" + area + "</b>");
//----------get weather conditions------------
$("#conditions").empty().append("<b>" + data.weather[0].description + "</b>");
//----------get wind speed------------
//get wind direction
var windSpeed = degToCompass(data.wind.deg);
//add wind speed
windSpeed += ' ' + data.wind.speed;
//display wind speed
$("#wind-speed").empty().append("<b>" + windSpeed + "</b>");
},
error: function (err) {
alert(err);
},
beforeSend: function (xhr) {
//xhr.setRequestHeader("X-Mashape-Authorization", "32ROUuaq9wmshfk8uIxfd5dMc6H7p1lqdZSjsnXkB5bQtBteLK"); // Enter here your Mashape key
}
});
});
Well... First of all there is no need to use WebServices, but you can't do it without any API. As I can see you use openweathermap API . As far as I know this API returns both longitude and latitude, so you can use these values as input to another request to a photo API (like flickr) to get the image you want. Moreover openweathermap API returns city name which can make your photo request even more accurate.
I'm creating a simple application to get the user's coordinates, plug them into the Forecast API, and get back the current weather. Things seem to be working smoothly for the first 2 parts but when it's all put together, the coordinates are not passed properly into the API call even though they are printed just fine. Pretty confused and appreciate any help.
<!DOCTYPE html>
<html>
<body>
<p>Here's the weather:<p>
<p id="weather"><p>
<p>Here's the coordinates:<p>
<p id="coordinates"><p>
<button onclick="b()">Submit</button>
<script>
function b(){
var apiKey = 'b04dbf475994a98f5849aa6856a4596d';
var url = 'https://api.forecast.io/forecast/';
var data;
var lati = 0;
var longi = 0;
navigator.geolocation.getCurrentPosition(getCoordinates);
function getCoordinates(position) {
lati = position.coords.latitude;
longi = position.coords.longitude;
}
$.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
console.log(data);
$('#weather').html(data.currently.temperature);
$('#coordinates').html(lati + "," + longi);
});
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</body>
</html>
Try adding the $.get into your function that collects the geolocation. I suspect that is asynchronous.
function getCoordinates(position) {
lati = position.coords.latitude;
longi = position.coords.longitude;
$.getJSON(url + apiKey + "/" + lati + "," + longi + "?callback=?", function(data) {
console.log(data);
$('#weather').html(data.currently.temperature);
$('#coordinates').html(lati + "," + longi);
});
}