Gmaps Callback function get variables [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
I have JS code which is doing geolocation, so I converted address to coordinates, but I can not get values from callback function:
$(function () {
var longitude;
var latitude;
GMaps.geocode({
address: geolocate_address,
callback: function(results, status) {
if (status == 'OK') {
var latlng = results[0].geometry.location;
latitude = latlng.lat();
longitude = latlng.lng();
}
}
});
console.log(latitude);
console.log(longitude);
});
Shows empty variables.
When I do alert in callback function it shows coordinates.
How to get coordinates outside that function?

Your callback is async, at the moment you invoke console.log(latitude);, latitude still does not have value set, as client is still waiting for server response.
Try to handle data after you receive it:
GMaps.geocode({
address: geolocate_address,
callback: function(results, status) {
if (status == 'OK') {
var latlng = results[0].geometry.location;
latitude = latlng.lat();
longitude = latlng.lng();
handleCallback(latitude, longitude);
}
}
});
function handleCallback(latitude, longitude){
console.log(latitude);
console.log(longitude);
}

Related

Javascript can't access global variables outside function [duplicate]

This question already has answers here:
Using a callback function with Google Geocode
(1 answer)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 4 years ago.
I'm using google map geocoding to get latitude,longitude value from address.Here is my code,
var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(place);
var latd = results[0].geometry.location.lat();
var lond = results[0].geometry.location.lng();
}
console.log(latd);
});
//console.log(latd);
When access the variable latd outside function, its value seems undefined. What's the issue with the above code?
Update1:
getlatlang(address);
console.log(latd);//Not defined
function getlatlang(address)
{
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//console.log(place);
latd = results[0].geometry.location.lat();
lond = results[0].geometry.location.lng();
return latd,lond;
}
});
}
If you want to have access to lat, long outside the function simply assign them and do not create them inside. You can read more about JavaScript Scope
var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(place);
latd = results[0].geometry.location.lat();
lond = results[0].geometry.location.lng();
}
console.log(latd);
});
//console.log(latd);
First, because the variable you try to access into your condition will be accessible only into the context if. The variable your redeclared into if is new variable.
if (status == google.maps.GeocoderStatus.OK) {
console.log(place);
var latd = results[0].geometry.location.lat();
var lond = results[0].geometry.location.lng();
console.log(latd, lond)
}
You can change with this:
var latd;
var lond;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(place);
latd = results[0].geometry.location.lat();
lond = results[0].geometry.location.lng();
}
console.log(latd);
});
Update
geocoder.geocode is an async function. You have to wait until it's done.
Your variable after the geocoder.geocod is executed even if the geocoder hasn't yet finished to be executed. So your variable is always undefined, because you create a variable with undefined value.
Note: All your action should be into the callback function, of geocoder, otherwise, it will always undefined.

Google map Geocoder [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)
Closed 6 years ago.
I Using the google geocoder to get the lat and lng, when initMap had been called, I got two alert, first value is undefined ,and second get the lat value, what is the problem to get the undefined value, and how to resolve this? I need to get the value immediately.
function initMap(){
var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
var code = getLatLng(addr);
alert(code.lat); // --> alert_1
}
function getLatLng(addr) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': addr }, function (results, status) {
var lat,lng = 0;
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
}
alert(lat); // --> alert_2
return {lat : lat,lng : lng};
});
}
The function geocode is an asynchronous function. Therefore, you get undefined for code.lat in the alert of the initMap function and the geocoded value in the getLatLng function. You can add a callback function to the parameters of the getLatLng function to solve your problem like this:
function initMap() {
var addr = '1600 Amphitheatre Parkway, Mountain View, CA';
getLatLng(addr, function(code) {
alert(code.lat);
});
}
function getLatLng(addr, cb) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': addr }, function (results, status) {
var lat,lng = 0;
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
}
cb({lat: lat, lng: lng});
});
}

Getting a Return Value From Google Maps Geocoder [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)
Closed 8 years ago.
I am trying to get a location name according to a lat-long coordinate from the Google maps geocoder. I cannot seem to extract the value from the geocoder callback. Here is my code:
geocoder = new google.maps.Geocoder();
var address = "";
var lat = 54.1234;
var lng = -114.1234;
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng } , function(results,status) {
if (status == google.maps.GeocoderStatus.OK) {
address = results[1].formatted_address; //want to get this address
} else {
address = 'error';
}
});
window.alert(address)
//address is an empty string here, but I want the value from inside the geocoder
//want access to address here to do other operations with it
The documentation for geocoder on the Google Developers site is almost non existant,
and I am having problems trying to find an example that is similar. I am out of my comfort area here, so any help
would be great!
The call is asynchronous, so the value exists inside the callback function:
geocoder.geocode({'latLng': latlng } , function(results,status) {
if (status == google.maps.GeocoderStatus.OK) {
address = results[1].formatted_address; //want to get this address
} else {
address = 'error';
}
window.alert(address);
});
// The code here runs before the callback function

How to assign a value to an outer variable from an inner function in javascript? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
So, I have this piece of code:
function centermap(){
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('office_address').value;
var new_location = "";
geocoder.geocode( {'address': address}, function(results, status, new_location) {
if (status == google.maps.GeocoderStatus.OK) {
new_location = results[0].geometry.location;
console.log(new_location); // output is fine here
}
else {
console.log("Geocode was not successful for the following reason: " + status);
}
})
console.log(new_location); // output is "" - which is the init value
return new_location // the returned object is also ""
};
$("input[id=office_address]").change(function(){
var coordinates = new Array();
var location = centermap();
coordinates.push(location.geometry.location.lat());
coordinates.push(location.geometry.location.lng());
map.setView(coordinates, 14);
});
What am I not getting regarding the scopes here? How can I set the "outside" new_location to be the gecode result? Please feel free to point all the mistakes on my understanding on this
EDIT: I have read the answers on this and this so questions but I didn't manage to do what I want.
As somebody pointed out in the comments, the geocode function is asynchronous, so as soon as it is executed it will return without any value.
Consider this workflow:
...
geocoder.geocode( ... );
// this is executed straight after you call geocode
console.log(new_location);
...
...
// probably at a certain point here your geocode callback is executed
function(results, status, new_location) {
if (status == google.maps.GeocoderStatus.OK) {
...
});
The important thing is to pass a callback function to your centermap as well:
$("input[id=office_address]").change(function(){
var coordinates = new Array();
// pass a callback to execute when geocode get the results
centermap(function (location){
coordinates.push(location.geometry.location.lat());
coordinates.push(location.geometry.location.lng());
map.setView(coordinates, 14);
});
});
function centermap(callback){
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('office_address').value;
geocoder.geocode( {'address': address}, function(results, status) {
var new_location = '';
if (status == google.maps.GeocoderStatus.OK) {
new_location = results[0].geometry.location;
console.log(new_location); // output is fine here
}
else {
console.log("Geocode was not successful for the following reason: " + status);
}
// at this point we return with the callback
callback(new_location);
});
// everything here is executed before geocode get its results...
// so unless you have to do this UNRELATED to geocode, don't write code here
};

How do you return a latitude and longitude array using the Google Javascript v3 Geocoder? [duplicate]

This question already has answers here:
Accessing array from outside of geocode loop
(2 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 years ago.
I'm trying to create a function that utilizes Google Javascript V3's geocoding capabilities and returns an array with the longitude and latitude. For some reason the return array is not being populated using the function. Thanks for your help!
Code:
function getCoords(address) {
var latLng = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng.push(results[0].geometry.location.lat());
latLng.push(results[0].geometry.location.lng());
return latLng;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
var test_arr;
test_arr = getLatLng('New York');
alert(test_arr[0] + ',' + test_arr[1]) // I'm getting a test_arr is undefined here.
Read up on using callback functions in Javascript. This article might be helpful.
As Jon pointed out, you can solve this by passing a callback function into your getCoords method. It's a way of waiting for the response to come back from Google. You define a function that will be called when the geocoding is done. Instead of returning the data, you'll call the provided function with the data as an argument.
Something like this:
function getCoords(address, callback) {
var latLng = [];
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latLng.push(results[0].geometry.location.lat());
latLng.push(results[0].geometry.location.lng());
callback(latLng);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
getCoords('New York', function(latLng) {
var test_arr;
test_arr = latLng;
alert(test_arr[0] + ',' + test_arr[1])
// Continue the rest of your program's execution in here
});
#Matt Ball should have posted the answer. :)
The reason test_arr is undefined is because you're evaluating it immediately before the results come back.
If you did a setTimeout (which you shouldn't do), you would notice eventually the array will have something in it.
setTimeout(function(){
alert(test_arr) // has stuff...
}, 5000);
Instead, you can pass an anonymous function to getCoords as a callback. This function gets executed once the coordinates are available.
function getCoords(address, callback) {
...
var lng = results[0].geometry.location.lng();
var lat = results[0].geometry.location.lat();
callback([lat, lng]);
...
}
getCoords("New York", function(coords) {
alert(coords); // works
});

Categories