user1661677
user1661677

Reputation: 1272

return JSON value out of function?

I'm trying to return a lat value out of a function using Google's Geocoder, but it's not working. I'm getting an error that says "unexpected token"?

function getLat(address) {
  var googleToken = "my-google-token"
  var geoUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + googleToken;
    $.getJSON(geoUrl, function(data) {
      return data.results[0].geometry.location.lat);
    });
}

$('body').html(getLat('New+York,+NY'));

Upvotes: 0

Views: 26

Answers (2)

adeneo
adeneo

Reputation: 318182

The async function needs a callback, or you can use promises

function getLat(address) {
    return $.getJSON('https://maps.googleapis.com/maps/api/geocode/json', {
       adress : adress,
       key    : "my-google-token"
    });
}

getLat('New+York,+NY').done(function(data) {
    $('body').html(data.results[0].geometry.location.lat);
});

Upvotes: 1

void
void

Reputation: 36703

The issue is loading an external resource using an XMLHTTPRequest is an async task.

Better and easy way of doing this is

function getLat(address, $el, type) {
  var googleToken = "my-google-token"
  var geoUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + googleToken;
    $.getJSON(geoUrl, function(data) {
      if(type=="html")
         $el.html(data.results[0].geometry.location.lat);
      else if(type=="text")
         $el.text(data.results[0].geometry.location.lat);
    });
}

getLat('New+York,+NY', $("body"), "html");
getLat('New+York,+NY', $("div"), "text");

Upvotes: 2

Related Questions