0

var address ="<%= params[:search] %>";
var lat;
var long;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
 lat = results[0].geometry.location.lat();
 long = results[0].geometry.location.lng();
}); 
alert(lat);
//wanna use lat and long here!

browser always alert "undefined" when called outside the function, works when called from within the function.

2 Answers2

0

Hello Ashutosh Gupta,

this happens because your alert() happens before variable assignment. You can use Promise to solve this issue, like

var address ="<%= params[:search] %>";
var lat;
var lng;
var geocoder = new google.maps.Geocoder();

new Promise((resolve, reject) => {
geocoder.geocode( { 'address': address}, function(results, status) {
    lat = results[0].geometry.location.lat();
    lng = results[0].geometry.location.lng();
    resolve({lat: lat, lng: lng});
}));
}).then((data) => {
    alert(data);
});
Sebastian Waldbauer
  • 674
  • 1
  • 10
  • 17
0

The geocoder.geocode function is asynchronous, and it receives latitude and longitude inside a callback function - after the asynchronous operation is complete. Only then the lat and long variables are defined.

Your alert runs immediately after starting the asynchronous operation, meaning that it's still not complete by the time the alert is fired. So, lat and long are still undefined.

You cannot use latitude and longitude outside of the callback block. Move it inside the callback block and it will work:

var address ="<%= params[:search] %>";
var lat;
var long;
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
    lat = results[0].geometry.location.lat();
    long = results[0].geometry.location.lng();
    // you can use lat and lng inside here! :)
    alert(lat);
});

Read this post if you want to get a better understanding of asynchronous code in JavaScript: https://stackoverflow.com/a/14220323/2401947

fmoliveira
  • 376
  • 4
  • 8