0

I've got a pretty basic function that grabs the users current location. When I alert or log the geoCoder variable I successfully get a value. I'm trying to put that geoCoder value inside of my JSON call.

function userLocation(location, callback) {
    var geoCoder = new google.maps.Geocoder();
        geoCoder.geocode({
            location: location
        }
    console.log(geoCoder);
}

var jsonCall;
jsonCall = '/bin/userlocation/locations.' + geoCoder + '.json'

When I run this I get a geoCoder is not defined js error. How would I go about getting the value of the geoCoder variable? I'm kind of a newb so code examples are appreciated.

Delmon Young
  • 2,013
  • 5
  • 39
  • 51

2 Answers2

1
var jsonCall; //declaring outside and before a function means the var will be accessible inside and outside of the function

function userLocation(location, callback) {
    var geoCoder = new google.maps.Geocoder();
        geoCoder.geocode({
            location: location
        }
    console.log(geoCoder);
    jsonCall = '/bin/userlocation/locations.' + geoCoder + '.json'
}

console.log(jsonCall);
Brian Ogden
  • 18,439
  • 10
  • 97
  • 176
  • This is not going to work. The `geocode` call is **A**synchronous. – Andrew Whitaker Oct 19 '13 at 23:46
  • Switched the vars around so it will work now, thanks! – Brian Ogden Oct 19 '13 at 23:48
  • @BrianOgden Thanks! This worked but out of curiosity why couldn't I put my jsonCall outside the userLocation function and still call the geocoder variable? – Delmon Young Oct 19 '13 at 23:56
  • so the var geoCoder is a google maps object, the geocode (geoCoder.geocode) method/property/function of the google maps object Geocoder is an asynchronous method and this gives direction to your inquiry but I am not exactly sure myself. Perhaps @AndrewWhitaker could elaborate on why my first answer didn't work but my update to my answer does. Also checkout this question on SO for further research: http://stackoverflow.com/questions/6129733/google-geocoder-asynchronous-issue – Brian Ogden Oct 20 '13 at 00:26
0

You are creating your variable in function and trying to reach at out of the scope of the function. Try to define it out of the function and assign the value wherever u want.

Define as var geoCoder; out of the function. and fill geoCoder in function.

var geoCoder;
function blabla(){
geocoder = dosomething
}

console.log(geoCoder); // this returns null
blabla();
console.log(geoCoder); // now u can see it is not empty
obayhan
  • 1,636
  • 18
  • 35
  • Okay I'm kind of a newb how would I go about doing that can you please provide a code sample as noted in my question. Thanks! – Delmon Young Oct 19 '13 at 23:45
  • Note what @Andrew Whitaker said, the geocode call is an Asynchronous function, see my answer, I just declared the jsonCall var before the function call so its in scope inside and outside the function – Brian Ogden Oct 19 '13 at 23:55