MJVDM
MJVDM

Reputation: 3963

Why is this variable undefined or not returned?

I have the following code:

/*
 * converts a string to geolocation and returns it
 */

function stringToLatLng(string){
    if(typeof string == "string"){
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': string}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
              console.log("LatLng: "+results[0].geometry.location);
              return results[0].geometry.location;
           } else {
              console.log("Geocode was not successful for the following reason: " + status);
           }
        });
   }
}

the LatLng prints the correct location to the console, but when I write this:

var pos = stringToLatLng('New York');
            console.log(pos);

I get undefined back. Why is that? thanks

Upvotes: 0

Views: 300

Answers (2)

Alvin Pradeep
Alvin Pradeep

Reputation: 618

var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();

ref: Javascript geocoding from address to latitude and longitude numbers not working

Upvotes: 0

Josh Mc
Josh Mc

Reputation: 10224

Something like this:

function stringToLatLng(strloc, callback){
    if(typeof string == "string"){
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'address': strloc}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
              callback.call({}, results[0].geometry.location);
           } else {
              console.log("Geocode was not successful for the following reason: " + status);
           }
        });
   }
}

stringToLatLng('New York', function(pos){
    console.log(pos);
});

In your code, when you return, you are actually returning from the function(results, status){..} function, not the stringToLatLng function, as said in the comments its an asynchronous call, so you must use a callback.

Upvotes: 2

Related Questions