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;
});
}
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*/
};
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();
I have the geoCode function that uses a callback function to do something after the asynchronous request has completed. However, it returns a NULL value.
function codeAddress(callback) {
/***** build string address from form data
var address = addressOne + "," + addressTwo + "," + region + "," + zip + "," + country;
*****/
var geocodeAddress = geocoder.geocode( { 'address': address}, function (results, status) { callback( results ) } );
}
codeAddress(function(returnData){
console.log("results= " + returnData);
console.log(returnData);
});
this gives empty array
var returnData = function () {
return data;
};
codeAddress (returnData ());
Should be able to pass what you like.
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 }
I have a script that allows the user to view locations of comms cabinets. I am trying to get html5 to pass latitude and longitude to a php script(geo.php) to update the record in the database with the map coordinates, but keep getting errors:
ReferenceError: Can't find variable: pos
this is my code. Please help me get the latitude and longitude to appear in the link to be called by ajax:
function getLocation() {
navigator.geolocation.getCurrentPosition(function(pos)
{
var lat = pos.coords.latitude;
var lng = pos.coords.longitude;
});
}
function saveLocation(building, commNo) {
getLocation();
var latitude = lat;
var longitude = lng;
alert(latitude + longitude);
document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
getMap(exchangeName, PCP);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
The geolocation API is asynchronous, just like your ajax call, so you have to wait for the results to return, and even if you did have to wait for the async call, variables are only available inside the scope where they are defined.
function getLocation(callback) {
navigator.geolocation.getCurrentPosition(function (pos) {
callback(pos.coords.latitude, pos.coords.longitude);
});
}
function saveLocation(building, commNo) {
getLocation(function(latitude, longitude) {
document.getElementById('maps').innerHTML = 'Saving <img src=\"img/ui-anim_basic_16x16.gif\">';
var strURL = "includes/geo.php?building=" + building + "&commNo=" + commNo + "&latlng=" + latitude + "," + longitude;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
getMap(exchangeName, PCP);
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
});
}