how to globalize a variable that is in a function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed last month.
I would like to ask you to help me solve the following question which is giving me trouble: How do I isolate the latitude and longitude variables to display them outside the function
navigator.geolocation.getCurrentPosition(getLatLon);
function getLatLon(position) {
var latitude = "";
var longitude = "";
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
document.write("Latitude is "+latitude);
document.write("Longitude is "+longitude);

var latitude;
var longitude;
navigator.geolocation.getCurrentPosition(getLatLon);
function getLatLon(position) {
latitude = "";
longitude = "";
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
document.write("Latitude is "+latitude);
document.write("Longitude is "+longitude)
declare them outside of the function or at the top of your script file(global variables)

Related

JS - Current position return undefinied [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How to access the correct `this` inside a callback
(13 answers)
unable to cope with the asynchronous nature of navigator.geolocation
(5 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I try to get my current browser location and set it in variables. If browser doesn't have activated geolocation set a default latitude and longitude.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(location) {
this.latitude = location.coords.latitude;
this.longitude = location.coords.longitude;
});
}else{
this.latitude = 43.318820;
this.longitude = -3.004561
}
console.log(this.latitude); //Undefinied
console.log(this.longitude);//Undefinied
The problem: Variables return undefinied in every cases. So, ¿What´s wrong in this code?
EDIT
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(location => {
this.latitude = location.coords.latitude;
this.longitude = location.coords.longitude;
});
}else{
this.latitude = 43.318820;
this.longitude = -3.004561
}
console.log(this.latitude);
console.log(this.longitude);

Reading Array of Json [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 2 years ago.
I have created a function that tries to get lat long based on the address and after that, I want those to print on console
How to get values of coords.... am I doing it in the correct way? please help to understand it.
coords = getLocationCoords("Ambala,Haryana,India,134003");
console.log(coords)
function getLocationCoords(fa){
var coords = [];
$.get(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q='+fa, function(data){
coords['lat'] = JSON.parse(data[0].lat);
coords['lon'] = JSON.parse(data[0].lon);
});
return coords;
}//getLocationCoords
You cannot get the coords as "returned value", because there is nothing to return. That is, nothing to return until some handler is invoked, which could be 0.2 seconds later, or 3 seconds later. But if the handler returns it, you still won't be getting it since the assignment happened immediately. To solve this, you can also just make it a "promise", so that when the value is ready, you can then() it, and process the value, like follows:
getLocationCoords("Ambala,Haryana,India,134003")
.then(data => {
coords = data.map(loc =>
({
lat: Number(loc.lat),
lon: Number(loc.lon)
})
);
console.log("GOT IT", coords);
});
function getLocationCoords(fa) {
return $.get(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q=' + fa)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Pass reference variable outside the function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
What is the scope of variables in JavaScript?
(27 answers)
Closed 3 years ago.
In a function to obtain certain data with a json, I want to use this data in a variable and then use it in another function. The problem is that it does not work for me
First of all, obtaining the data with a json and printing it in place on the screen, until now, the problem starts when I save the data in a variable
function cargarPropuestas() {
var peticionLoc = new XMLHttpRequest();
peticionLoc.open('GET', 'https://api.ipdata.co/es?api-key=b3ae31a7a74386088875d7d285250b58778e13de985b2f561910b6bd');
peticionLoc.onload = function () {
var datosLoc = JSON.parse(peticionLoc.responseText);
var elementoLoc = document.createElement('div');
elementoLoc.innerHTML += (datosLoc.city + ', ' + datosLoc.country_name);
loc.appendChild(elementoLoc);
var country = datosLoc.country_name;
}
peticionLoc.send();
What interests me here is the variable COUNTRY
And here the problem begins, since when I "leave" the requestLoc.onload = function () {} I can not call the variable COUNTRY to use it below
What I need is to know how to get the information of this variable out of the function, in order to use that data
You can declare country outside both functions.
var country;
function cargarPropuestas() {
//...
peticionLoc.onload = function () {
//...
country = datosLoc.country_name;
}
peticionLoc.send();
}

Javascript - can console.log an object inside a function but when returned it is comes back as undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to write a function to geocode a zipcode, and return the lat and lng to an object, and then return this object. I am then trying to assign the value of this geocode function to a variable to create an object.
When I console log the object created in this function, I get an object returned in my terminal as expected:
const geo = (zip) => {
geocoder.geocode(zip, function(err, data) {
let latLng = {};
latLng.lat = data.results[0].geometry.location.lat;
latLng.lng = data.results[0].geometry.location.lng;
console.log(latLng); // Returns Object As Expected
});
};
But when I instead replace the console.log(latLng) with return latLng I get an undefined value when assigning this function to a variable like so:
let newObj = geo(zip);
console.log(newObj) // Returns Undefined
I am confused because the initial console.log does show an object is being made in the geocode function, but when I use return it is coming back as undefined. I think it is an issue with how I am assigning it to a variable. I am misunderstanding something without doubt.
The problem is you are mixing async (via callbacks with sync), you could use promises to simplify this
const geo = (zip) => {
return new Promise(resolve => {
geocoder.geocode(zip, (err, data) => {
let latLng = {};
latLng.lat = data.results[0].geometry.location.lat;
latLng.lng = data.results[0].geometry.location.lng;
resolve(latLng);
});
})
};
you can utilise the function then like
geo(zip).then(latLng => {
console.log(latLng) // or whatever
})
You didn't specify a return statement. Avoid the arrow in this case and just use a normal function. .geocode() method return value is not assigned in any way. You need to keep throwing the value back to its caller.
const geo = function(zip) {
return geocoder.geocode(zip, function(err, data) {
let latLng = {};
latLng.lat = data.results[0].geometry.location.lat;
latLng.lng = data.results[0].geometry.location.lng;
console.log(latLng); // Returns Object As Expected
return latLng;
});
};
You can try async-await because geocode method is asynchronous.
Reference: How to make this method asynchronous?

Returning values from nested functions - JavaScript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm having some trouble returning the latLng value for the following function.
function getUserPosition() {
var latLng;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); // #1
}, function () {
latLng = defaultPosition(); // #2
}
);
} else {
latLng = defaultPosition(); // #3
}
return latLng;
}
Assume that defaultPosition() returns a valid set of coordinates.
I've marked three latLng assignments that are part of my latest 'catch-all' approach but still no luck.
I've checked out other related answers but still can't seem to get my head around my particular issue, so sorry for the repost.
Thanks in advance.
You can't do that because of the asynchronous nature of the location API, instead you need to use a callback based approach where the callback function will be invoked once the locaion API returns the value.
function getUserPosition(callback) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
callback(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
}, function () {
callback(defaultPosition()); // #2
});
} else {
callback(defaultPosition()); // #3
}
}
getUserPosition(function(latLng){
//do all operations that depends on latLng here in the callback function
})

Categories