0

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

MJB
  • 3,934
  • 10
  • 48
  • 72
  • 2
    Because `.geocode` is asynchronous – zerkms Sep 17 '12 at 21:59
  • Why does that imply in this case? I mean LatLng was printed correctly to the console... how can I fix it then? I mean, how can I "wait" until the result is ready? – MJB Sep 17 '12 at 22:01
  • you don't need to wait - put all the code that works with results in a callback, as you've already done with `console.log` – zerkms Sep 17 '12 at 22:07

2 Answers2

2

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.

Josh Mc
  • 9,911
  • 8
  • 53
  • 66
  • I had tried the above snippet, it is returning the value, it shows up in alert ,but when i try to assign it to some variable or give that alert outside the function it is null again....any help plz... – mandava Jan 16 '13 at 12:58
  • i am getting a is null error along with that will it cause some problem in this scenario.... – mandava Jan 16 '13 at 13:00
  • It is probably because you are trying to use the variable outside the stringToLatLng('New York', function(pos){ console.log(pos); }); method, Make sure you are using it directly after the alert. – Josh Mc Jan 18 '13 at 07:45
0
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

Community
  • 1
  • 1
Alvin Pradeep
  • 618
  • 4
  • 13