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.
Related
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});
});
}
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);
}
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
};
What I want to do is that I need to create markers from stored location of user. So for that I need latitude and longitude. I got the lat & lon in my function get_current_user_lat_lon . Now I want to return both lat & lon through Object but my return is not working....
function initialize(){
var var_get_current_user_lat_lon = get_current_user_lat_lon();
var latitutde = var_get_current_user_lat_lon.latitutde;
alert(latitutde);// not even alert
var longitutde = var_get_current_user_lat_lon.longitutde;
alert(longitutde); // not even alert
}
function get_current_user_lat_lon(){
var address = $("#hidden_current_location").val();//Working fine
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var variable = results[0].geometry.location;
var lat = variable.lat();
var lon = variable.lng();
alert(lat); //Working fine
alert(lon); //Working fine
//return not working here
}
//return not working here
});
return {latitutde: lat , longitutde : lon};// giving error lat.lon is not defined means return not working here
}
Your "lat" and "lon" variables are declared inside the callback from "geocode()". Even if you declared them outside it, however, the overall idea would not work. The "geocode()" function is asynchronous; that's the reason there's a callback function in the first place.
Instead of structuring your code so that your "get_current_user_lat_lon()" function returns a value, follow the lead of the Google architecture and make your own function take a callback:
function get_current_user_lat_lon( callback ){
var address = $("#hidden_current_location").val();//Working fine
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var variable = results[0].geometry.location;
var lat = variable.lat();
var lon = variable.lng();
callback({latitude: lat, longitude: lon});
}
});
}
How could I get the value from test2 variable passed on to another function? I've been trying with global variables and by chaining functions, as suggested in another thread I found, but couldn't get those to work.
function codeAddress(addresstocode) {
var test2 = ['123','321'];
geocoder.geocode( { 'address': addresstocode}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
coded_lat = results[0].geometry.location.Ka;
coded_long = results[0].geometry.location.La;
//coded_location = [{"latitude" : coded_lat, "longitude" : coded_long}];
//test2 = returnAddress(coded_location);
test2 = [coded_lat,coded_long];
//coded_lat = coded_location[0].latitude;
//coded_long = coded_location[0].longitude;
//returnAddress(coded_location);
}
});
console.log('test2: '+test2);
return test2;
}
You have to create a function that receives the values like :
function geocodeOK(lat, lng){
// Do what you want with lat lng
}
And in your code :
function codeAddress(addresstocode) {
var test2 = ['123', '321'];
geocoder.geocode({
'address': addresstocode
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
coded_lat = results[0].geometry.location.Ka;
coded_long = results[0].geometry.location.La;
geocodeOK(coded_lat, coded_long);
}
});
}
You should also never use the letter designations of location.Ka, location.La. The "Ka" and "La" change often. Use the appropriate functions of location.lat() or location.lng(). That way your code doesn't break all of a sudden.