var x = document.getElementById("demo");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
var location = position.coords.latitude +
"," + position.coords.longitude;
jQuery(document).ready(function($) {
$.ajax({
url : "https://api.wunderground.com/api/0ce1c4a981f7dd2a/geolookup/conditions/q/"+location+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
x.innerHTML = "Current temperature in " + location + " is: " + temp_f;
var forecast = parsed_json['forecast']['txt_forecast']['forecastday'];
for (index in forecast) {
var newForecastString = '' + forecast[index]['title'] + ' سيكون ' + forecast[index]['fcttext_metric'];
var newForecastParagraph = $('<p/>').text(newForecastString);
$(".astro").append(newForecastParagraph);
}
}
}});
I'm trying to make a weather that first checks for jQuery on a page and loads the library if necessary, before loading my custom script. The script looks like this
This is the corrected one.
You can test your javascript here: http://www.javascriptlint.com/online_lint.php
var x = document.getElementById("demo");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
function showPosition(position) {
var location = position.coords.latitude + "," + position.coords.longitude;
jQuery(document).ready(function($) {
$.ajax({
url : "https://api.wunderground.com/api/0ce1c4a981f7dd2a/geolookup/conditions/q/"+location+".json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
x.innerHTML = "Current temperature in " + location + " is: " + temp_f;
var forecast = parsed_json['forecast']['txt_forecast']['forecastday'];
for (index in forecast) {
var newForecastString = '' + forecast[index]['title'] + ' سيكون ' + forecast[index]['fcttext_metric'];
var newForecastParagraph = $('<p/>').text(newForecastString);
$(".astro").append(newForecastParagraph);
}
}
});
});//add this code. Need to close the 'jQuery(document)'
} // added this code. Need to close the function showPosition
Last line is missing ) in second position. it should be })});
the last 3 lines of your code are as follows
}
}
}});
however, they should be
}
}
}); // you missed this );
});
} // you missed this }
Related
I want the longitude and latitude passed from the geolocation function to my getjson function so that i can pull certain info like temperature, condition etc. What am i doing wrong that the lati and loni are not being passed properly? Are my functions set up correctly?
$(window).load(function() {
getLocation();
apiCall();
}); //run immediately on page load
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var lati = position.coords.latitude;
var loni = position.coords.longitude;
function passData(lati, loni);
}
var weath = 0;
function apiCall() {
function passData(latitude, longitude) {
var lati = latitude;
var loni = longitude;
x.innerHTML = "Latitude: " + lati +
"<br>Longitude: " + loni;
}
//$(".city").html(data.city + "," + "" + data.countryCode);
$.getJSON("https://fcc-weather-api.glitch.me/api/current?lat=" + lati + "&lon=" + loni, function(data1) {
weath = Math.round(data1.main.temp);
$(".temp").html(weath + " " + "℃");
$(".condition").html(data1.weather[0].description);
$(".iconDisplay").append('<img src=' + data1.weather[0].icon + '/>');
}); /*end of json*/
};
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 using geolocation to get my own latitude and longitude,but the console always return undefined,btw when I clicking the tiy geolocation toturial on w3chool the response is "Location information is unavailable".
var lati,lgi;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
console.warn("Your browser don't support geoloction!");
}
function success(pos) {
console.log(pos);
var cr;
cr = pos.coords;
lati= cr.latitude;
lgi = cr.longitude;
console.log(lati+","+lgi);
}
function error(err) {
console.warn("ERROR(" + err.code + "): " + err.message);
}
updated:I use dark-sky api to get some weather JSON,the remaining code updated.
function getData() {
var userkey = "***my key***";
var site = "https://crossorigin.me/https://api.darksky.net/forecast/";
var reqstr = site + userkey + lati + "," + lgi;
console.log(reqstr);
var data;
$.getJSON(reqstr, function(result) {
data = JSON.parse(result);
});
console.log(data.latitude);
}
getData();
All in this code I'm trying to give user location and Temperature in locality But somehow temperature is showing way less in Celsius and also not updating below is what I tried like it is 4-5 Hours Back Data that to 10 degree Celsius less like if temp is 22(Celsius) hours back it is showing like 3(Celsius) working Example On codepen http://codepen.io/cannelflow/full/RrymYo/
var x = document.getElementById("demo");
var y = document.getElementById("demo1");
window.onload = getLocation();
//window.onload=getWeather();
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
//Location For Display
function showPosition(position) {
var loc = { lat: position.coords.latitude, lon: position.coords.longitude };
getWeather(loc);
var baseURL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=";
var fullURL = baseURL + loc.lat + "," + loc.lon;
$.ajax({
url: fullURL,
success: function (display) {
x.innerHTML = display.results[1].formatted_address;
}
});
}
//Location For Weather
function getWeather(loc) {
var baseURL = "http://api.openweathermap.org/data/2.5/weather?lat=";
var appid = "064129b86c99c35c42d531db251b99e3";
var fullURL = baseURL + loc.lat + "&lon=" + loc.lat + "&appid=" + appid + "&units=metric";
//http://api.openweathermap.org/data/2.5/weather?lat=21.2600668&lon=81.5989561&appid=064129b86c99c35c42d531db251b99e3&units=metric
$.ajax({
url: fullURL,
success: function (display1) {
y.innerHTML = display1.main.temp;
}
});
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
<body>
<section>
<div class="container-fluid text-center">
<br />
<!-- <h1><button class="btn btn-danger" onclick="getLocation()">Click Me To Get Your Location!</button></h1> -->
<h1 class="text-primary" id="demo1"></h1>
<br />
<h1 class="text-primary" id="demo"></h1>
</div>
</section>
</body>
You have a typo:
var fullURL = baseURL + loc.lat + "&lon=" + loc.lat + "&appid=" + appid + "&units=metric";
should be
var fullURL = baseURL + loc.lat + "&lon=" + loc.lon + "&appid=" + appid + "&units=metric";
You have a typo in the query string. A better alternative is to user jQuery.param to build the query string from an object instead as its easier to read and thus less error prone.
function getWeather(loc) {
var baseURL = "http://api.openweathermap.org/data/2.5/weather?";
return $.ajax({
url: baseURL + $.param({
appid: "064129b86c99c35c42d531db251b99e3",
lon: loc.lon,
lat: loc.lat,
units: "metric"
}),
success: function(display1) {
y.innerHTML = display1.main.temp;
}
});
}
Modified It Like
function getWeather(loc) {
var baseURL = "http://api.openweathermap.org/data/2.5/weather?lat=";
var appid = "064129b86c99c35c42d531db251b99e3";
//var fullURL = baseURL + loc.lat + "&lon=" + loc.lat + "&appid=" + appid + "&units=metric";
//http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139&appid=44db6a862fba0b067b1930da0d769e98&units=metric
$.ajax({
url: baseURL,
type: 'get',
dataType: 'JSONP',
data: { lat: loc.lat, lon: loc.lon, units: 'metric', APPID: appid },
success: function (data) {
y.innerHTML = data['main']['temp'] + " °C";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
And It Worked
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm trying to create a simple function to return user location based on browser but it keeps returning undefined:
function getLocation() {
//get current location
var geo_param;
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// Create geolocation parameter
geo_param = "geolocation=[" + position.coords.latitude + "," + position.coords.longitude + "]";
console.log(geo_param)
});
}
return geo_param
}
function search(activity) {
var searchUrl = "/s?activity=" + activity + "&" + getLocation()
window.location.href = searchUrl;
console.info(searchUrl)
}
The getCurrentPosition scope is asynchronous, so geo_param will be returned before getCurrentPosition finished runnning. An solution to this is using a callback, see my example below.
function getLocation(callback, activity) {
//get current location
var geo_param;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
// Create geolocation parameter
geo_param = "geolocation=[" + position.coords.latitude + "," + position.coords.longitude + "]";
console.log(geo_param);
callback(geo_param, activity);
});
}
}
function search(activity) {
getLocation(search_with_current_location, activity);
}
function search_with_current_location(geo_param, activity) {
var searchUrl = "/s?activity=" + activity + "&" + geo_param;
window.location.href = searchUrl;
console.info(searchUrl);
}
In this case, your function executes before the response is being fetched. You need to have a callback function once you get the response from the API.
Also note you did not have query string key geo_param in redirection URL
Try this:
function getLocation(cb) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geo_param = "geolocation=[" + position.coords.latitude + "," + position.coords.longitude + "]";
if (typeof cb === 'function') {
cb(geo_param);
}
});
}
}
function search(activity) {
getLocation(function (geo_param) {
window.location.href = "/s?activity=" + activity + "&" + geo_param;
});
}