Search code examples
javascriptgoogle-mapspositiongeocode

Function not returning position object from googlemaps geocode


I have a function that gets the latLng from an adress with googles geocode.

function geoCode(address){
    var geocoder = new google.maps.Geocoder;
    geocoder.geocode({'address': address}, function(results, status) {
      if (status === 'OK') {
        var pos = {
            lat:results[0].geometry.location.lat(),
            lng:results[0].geometry.location.lng()
        };
        return pos;
      } else {
        alert('Geocode was not successful for the following reason: ' + status);
      }
    });
}

When I console log the "pos" object in this function I get the positions, but when i try to console.log it in an other function for example the one below

function foo(){
    var pos = geoCode(place);
    console.log(pos.lat);
}

I get the following alert: TypeError: undefined is not an object (evaluating 'pos.lat')

There seems something wrong with the return of the pos object.


Solution

  • Like geocodezip said your geoCode function is asynchronous. This means that when you call it from your foo function, foo finishes before it gets data back from geoCode which is what gives you your undefined error. What you can do is wrap your geoCode function in a Promise and resolve the promise with the data from google.