javascript return value is always undefined - javascript

I'm trying to retrieve the 2 attributes of seprated function and I debug there values before the end of the function and they have a value but the return value is alwas undifined I don't know why !!
the .js file
function STAAPlanlat(){
alert ("the function");
if (navigator.geolocation) {
//we supposed to call the handlers of the expections
navigator.geolocation.watchPosition(function(position) {
alert("show position ");
// x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;
var lat=position.coords.latitude;
var lan=position.coords.longitude;
//x.innnerHTML=out
alert(lat+"<"+lan);
return lan;
});
} else {
alert("error");
}
}
I got the alert with the values of the lan and lat
but when I call on separated file it return undefined return value
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="STAAP1.2.js"> </script>
<script type="text/javascript">
function test(){
var out=STAAPlanlat();
document.getElementById("STAAPlanlat").value = "lan is"+out;
//document.writeln("lan is"+out);
}
</script>
</head>
<body>
<p id="STAAPlanlat">Test the division</p>
<button onclick="test()">STAAPlanlat()</button>
<button onClick="alertme()" >Alert</button>
</body>
</html>

Cause you're not returning it from the main function, you're returning it from the embedded anonymous function which isn't doing anything with it. Do this:
function STAAPlanlat(){
var lat;
var lan;
alert ("the function");
if (navigator.geolocation) {
//we supposed to call the handlers of the expections
navigator.geolocation.watchPosition(function(position) {
alert("show position ");
// x.innerHTML="Latitude: " + position.coords.latitude +"<br />Longitude: " + position.coords.longitude;
lat=position.coords.latitude;
lan=position.coords.longitude;
//x.innnerHTML=out
alert(lat+"<"+lan);
});
return lan;
}
else
alert("error");
}

You are returning in the anonymous function and this value is never assigned to anything. You can do what you want with a callback.
// untested code, hope it works
function STAAPlanlat(callback){
alert ("the function");
if (navigator.geolocation) {
navigator.geolocation.watchPosition(function(position) {
var lat=position.coords.latitude;
var lan=position.coords.longitude;
callback(lat, lan);
});
}
else{
alert("error");
}
}
And your test function...
function test(){
var out;
STAAPlanlat(function(lat, lon) { out = lat; });
}

because function STAAPlanlat doesn't return any value. your anonymous function returns lan but it is asynchronous callback.
add this before return lan;:
document.getElementById("STAAPlanlat").value = "lan is" + lan;

Related

GPS location is fetched after second click not on first click

I want to fetch live gps location using javscript to store it in database. I already have implemented it. when user clicks on button. But it fetches location on second click.
Html code
<form action="user_location" method="post" id="form-{{$user->id}}">
#csrf
<input type="hidden" name="id" value="{{$user->id}}">
<input type="hidden" name="location" id="location-{{$user->id}}">
</form>
<a onclick="getLocation({{$user->id}})" class="btn">{{__('Get Location')}}</a>
Javscript code
function getLocation(user_id) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
geolocation = "Geolocation is not supported by this browser.";
}
if(setlocation){
form = document.getElementById("form-"+user_id);
var b = document.getElementById("location-"+user_id)
b.value = x.textContent;
form.submit();
}
}
function showPosition(position) {
x.innerText = position.coords.latitude + "-" + position.coords.longitude;
setlocation = true;
}
The getCurrentPosition function is asynchronous. That means that when it is called, it will allow the code after it to run before finishing. So that means that setLocation will not be true whenever your code reaches the following if statement:
if(setlocation){ // setlocation is still false
Handle your results of getting the position inside the success callback of getCurrentPosition.
function getLocation(user_id) {
if (!navigator.geolocation) {
return;
}
const form = document.getElementById("form-" + user_id);
const location = document.getElementById("location-" + user_id);
navigator.geolocation.getCurrentPosition(function(position) {
const { coords } = position;
location.value = coords.latitude + "-" + coords.longitude;
form.submit();
});
}

How get jQuery data in console

I see return data in console but
data.results[0].address_components[4].long_name;
I didn't take data when is test undefined but
x.innerhtml = data.results[0].address_components[4].long_name;
I see city name.
How can I do it?
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
var x = document.getElementById("demo");
var sonuc;
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 = "Latitude: " +position.coords.latitude+
//"<br>Longitude: "+position.coords.longitude;
var locAPI="https://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude+","+position.coords.longitude+"&key=xxxxxxxxxxxxxxhnfV2NWg&sensor=false";
$.get({
url:locAPI,
success:function(data){
console.log(data);
sonuc=data.results[0].address_components[4].long_name;// i didn' taka data
}
});
x.innerHTML=sonuc;
$.get("giden.php",{"city":sonuc},function(get_veri){
$(".veri").text(get_veri) });
//x.innerHTML=locAPI;
}
If I understand correctly, you're not sure why you are able to console.log(data) in your success callback function but when you try to render the data.results[0].address_components[4].long_name; to your html it renders undefined.
The reason why this is happening is because your success callback is asynchronous and you are appending the sonuc value before the success callback get's fired. What you should do is abstract out the logic for appending data.results[0].address_components[4].long_name; to your html into another function. This new function should be executed in your success callback. This way you are only setting x.innerHTML once you have a successful request and have actual data.
See the code below.
$.get({
url:locAPI,
success:function(data){
renderWhenDataIsValid(data)
}
});
function renderWhenDataIsValid(data){
sonuc=data.results[0].address_components[4].long_name;
x.innerHTML=sonuc;
$.get("giden.php",{"city":sonuc},function(get_veri){
$(".veri").text(get_veri)
});
}
I've also added a working example on jsfiddle you just need to supplement your API key.

Uncaught SyntaxError: missing ) after argument list3

var yourName; //global variable accessible to all functions
function showAnotherMessage() {
alert("Hi " + yourName ".\nThis is an alert message is no longer defined\nin the HTML but in a JavaScript file");
}
function init() {
yourName = Prompt("Hi. Enter your name.\nWhen the browser window is first loaded\nthe function containing this prompt window is called.", "Your name");
clickme = document.getElementById("clickme");
clickme.onclick = showAnotherMessage;
}
window.onload = init();
function showAnotherMessage() {
alert("Hi " + yourName + ".\nThis is an alert message is no longer defined\nin the HTML but in a JavaScript file");
}
you miss a "+" in your alert.
You are missing a + in your alert concatenation.
alert("Hi " + yourName + ".\nThis is an alert message is no longer defined\nin the HTML but in a JavaScript file");
Pass to the window.onload not the result of the function, but the reference of the function and add missed + in the alert's message
alert("Hi " + yourName + ".\nThis is an alert message is no longer defined\nin the HTML but in a JavaScript file");
Reference
window.onload = init;
You are missing a concatenation.
Prompt should be in lower case.
var yourName; //global variable accessible to all functions
function showAnotherMessage() {
alert("Hi " + yourName + ".\nThis is an alert message is no longer defined\nin the HTML but in a JavaScript file");
}
function init() {
yourName = prompt("Hi. Enter your name.\nWhen the browser window is first loaded\nthe function containing this prompt window is called.", "Your name");
clickme = document.getElementById("clickme");
clickme.onclick = showAnotherMessage;
}
window.onload = init();
if the issue is still there,, then it is related to calling the function
clickme.onclick = showAnotherMessage;
// instead use below
clickme.onclick = showAnotherMessage();

Empty Values in HiddenFields with Javascript

I'm calling the HTML geolocation method to get latitude and longitude and then storing them into 2 separate HiddenFields. These values from the HiddenFields will then be used in the server side (code behind) which will be stored in a table in my database. I searched high and low over stackoverflow to get help for empty values in HiddenFields, saving latitude and longitude into database, client and server side button click, etc.
I'm actually firing this javascript method based on a button, or do you think it's better to be fired window.onload?
I suspect that the functions aren't fired as well.. I have little knowledge on javascript.. Appreciate any help..
Javascript codes and HiddenFields in my WebForm:
<asp:HiddenField runat="server" ClientIDMode="Static" ID="latitudeTB"/>
<asp:HiddenField runat="server" ClientIDMode="Static" ID="longitudeTB"/>
<script type="text/javascript">
function HideLabel() {
var seconds = 3;
setTimeout(function () {
document.getElementById("<%=ErrorPanel.ClientID %>").style.display = "none";
}, seconds * 1000);
};
//GeoLocation Retrieval
var latJS = 0;
var lngJS = 0;
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
//position.coords.latitude + "," + position.coords.longitude;
//var lat = document.getElementById("<%=latitudeTB.ClientID %>");
latJS = position.coords.latitude;
lngJS = position.coords.longitude;
document.getElementById("<%= latitudeTB.ClientID %>").value = latJS;
document.getElementById("<%= longitudeTB.ClientID %>").value = lngJS;
alert(document.getElementById("<%= latitudeTB.ClientID %>").value + " " + document.getElementById("<%= longitudeTB.ClientID %>").value);
/*if (lat) {
lat.value = position.coords.latitude;
}*/
//var long = document.getElementById("<%=longitudeTB.ClientID %>");
/*if (long) {
long.value = position.coords.longitude;
}*/
}
function call() {
getLocation();
showPosition(position);
}
</script>
FYI. The button is placed above the HiddenFields and Javascript..
Codes for asp:Button:
<asp:Button ID="BTN_Login" CssClass="btn btn-theme-dark" Text="Login" runat="server" OnClientClick="call();" OnClick="BTN_Login_Click" />
I did actually print out the values of the hiddenfields on server side but i'm getting no values at all..
Debug.WriteLine(latitudeTB.Value);
Debug.WriteLine(longitudeTB.Value);
I hope that the code i added is sufficient..
Setting this on button click event or on window load event boils down to what you what the user experience to be.
Most websites tend to show the geolocation prompt when the DOM is ready.
You need to tweak your getLocation function. getCurrentPosition takes success and error callbacks, both of which are not being passed.
function getLocation(opts) {
return new Promise(function(resolve, reject) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition( resolve,
reject,
opts
);
}
else {
reject(new ReferenceError('Browser does not support geolocation api'));
}
});
}
You can then use it this way:
function setLatLong(latId, longId) {
getLocation()
.then(function(pos) {
var coords = pos.coords;
document.getElementById(latId).value = coords.latitude;
document.getElementById(longId).value = coords.longitude;
})
.catch(function(err) {
// log or fall back to come other Location API?
})
}
function call() {
setLatLong(
"<%= latitudeTB.ClientID %>",
"<%= longitudeTB.ClientID %>");
}
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition

Javascript Geolocation: Storing coordinates in an array

I created an HTML button:
...onclick="stLoc();"/>
which gears the stLoc() Javascript function.
My intention is to store the latitude inside the vaulesXarray.
Here's my code:
var valuesX=[];
//This is to show the current position:
function handleLoc(pos) {
var a=pos.coords.latitude;
var b=pos.coords.longitude;
var p = new L.LatLng(+a, +b);
mark(p);
}
//Here I intend to store the latitude using "valuesX.push":
function stLoc(pos) {
var a=pos.coords.latitude;
var b=pos.coords.longitude;
var p = new L.LatLng(+a, +b);
mark(p);
valuesX.push(a);
}
//And this is to enable the geolocation:
function handleErr(pos) {
document.write("could not determine location");
}
if (navigator.geolocation) {
navigator.geolocation.watchPosition(handleLoc,handleErr);
}
else {
document.write("geolocation not supported");
}
The output I get is an empty array.
Your stLoc() function is expecting pos object to be passed as first parameter.
But in your HTML part of example you're not passing this parameter to function:
<a "onclick="stLoc();">
This causes the error and the application flow breaks.
Update:
button
<script type="text/javascript">
var valuesX=[],
lastPos={a: -1, b: -1};
//This is to show the current position:
function handleLoc(pos) {
// in event handler remember lastPos to use it in stLoc on click.
lastPos.a = pos.coords.latitude;
lastPos.b = pos.coords.longitude;
var p = new L.LatLng(lastPos.a, lastPos.b);
mark(p);
}
//Here I intend to store the latitude using "valuesX.push":
function stLoc() {
if(lastPos.a != -1) {
valuesX.push(lastPos.a);
}
return false;
}
//And this is to enable the geolocation:
function handleErr(pos) {
document.write("could not determine location");
}
if(navigator.geolocation) {
navigator.geolocation.watchPosition(handleLoc,handleErr);
}
else {
document.write("geolocation not supported");
}
</script>
For guys looking out for code to implement this functionality in a different way..
Here is the code
<script language="javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script language="javascript">
function geoSuccess(e){
var lat = e.coords.latitude;
var lon = e.coords.longitude;
var myLoc = "Latitude: " + lat + '<br />Longitude: ' + lon;
$("#mylocation").html(myLoc);
}
function geoFailed(e){
$("#mylocation").html("Failed");
}
window.onload=function(e){
if ( navigator.geolocation){
navigator.geolocation.getCurrentPosition(geoSuccess, geoFailed);
} else {
// Error (Could not get location)
$("#mylocation").html("Failed");
}
}
</script>
<div id="mylocation"></div>

Categories

Resources