0

I am trying to find a set of latitude longitude values and assign it to a variable. My code looks like this

var k = findLattitudeLongitude("Italy");
console.log(k) // comes undefined
function findLattitudeLongitude(input){
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': input}, function(results, status) {
      var location = results[0].geometry.location;
        return location;

    });
   }

but it comes as undefined. What is the best way to achieve the above requirement. Is there any other method?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user1371896
  • 2,192
  • 7
  • 23
  • 32
  • possible duplicate of [Why is this variable undefined or not returned?](http://stackoverflow.com/questions/12467690/why-is-this-variable-undefined-or-not-returned) – geocodezip Aug 21 '13 at 16:18

2 Answers2

1

it's strange that the function return undefined, what you can do is to call another function, this way work with me fine, you can pass latitude and longitude params like the code below or the whole object

$( document ).ready(function() {
function   getlatlan(){
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "Italy"}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
         dosome(results[0].geometry.location.nb,results[0].geometry.location.mb)
     return true;

    ;
}});
}
function dosome(lat,lng){
console.log(lat,lng);
}
getlatlan();
});
Khaled Hasania
  • 335
  • 6
  • 14
1

Actually what you've done is correct.

The problem is the response received from Google geocoder is taking some time.

I've created a fiddle for a better understanding.

Praveen
  • 55,303
  • 33
  • 133
  • 164
  • so wht is the best way to do this?? Is there anyother way or solution to get thse lattitude longitude values? – user1371896 Aug 21 '13 at 09:29
  • The thing is that I am trying to find a best way to find lattitude longitude values using the function findLattitudeLongitude("Italy") , – user1371896 Aug 21 '13 at 09:37
  • yup, I understood. We have to wait till is response from Google geocoder. Let me try it. Do you need the value to be returned to k? – Praveen Aug 21 '13 at 09:39
  • yes!!! thats wht Im trying to get.. I have a value stored in array ["Italy", "Mexico", ... ] and I wanna find the lat long values one by one parsing thru the array.. I just added Italy as sample in my question – user1371896 Aug 21 '13 at 09:43
  • Check the fiddle Ive created.. from your above code.. http://jsfiddle.net/bD9yM/5/ it has 18 elements in country array.. but when the result comes.. alerts for lat long are only for 10 or 12 – user1371896 Aug 21 '13 at 10:32