0

I have a function, getLatLong() that I use throughout my code. I want it to return the latitude and longitude from a given address.

function getLatLong(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {

         lat = results[0].geometry.location.lat(); 
         lng = results[0].geometry.location.lng();
         return [lat, lng];

     } else {
         return ("Unable to find address: " + status);
     }
});

}

Wanting to be able to do getLatLong("London SW1A 1AA"); I seem to not be able to get it to work. It constantly returns undefined. After researching a bit, I see that I have to use a callback, but I cannot for the life of me figure out how to do it.

J. Doe
  • 1
  • 1
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas Sep 19 '16 at 20:05

1 Answers1

0

Are you sure you want to stick with Google Geocoding API? You could try the HTML5 Geolocation API using this MDN doc. This API is very new and so be sure to check out the browser compatibility at w3schools

Bharath
  • 96
  • 6
  • Sadly, that wouldn't work since I have multiple different adresses I need to convert to Lat and Lng. – J. Doe Sep 19 '16 at 20:22
  • In case you haven't realized yet, you have used a callback in your code. the anon func within your geocode() method is the callback function. It returns either an array or a string. So store that in a var like var result = getLatLong() and check type of var using typeof and then handle if its an array or a string. By the way, the else part inside your anon func shouldn't be returning the string like return ("..."+str) but instead return ""+str; Hope this helps. – Bharath Sep 19 '16 at 20:52