1

I have been using JavaScript and jQuery for a while now. But I still haven't fully grasped how it all works. I profusely apologize if my question is redundant, incomprehensible and/or plain stupid.

I am using Google Maps API v3 in combination with jQuery (no plugins, just plain jQuery) to populate a div#googleMap with map of London. In addition to that, I'm trying to write a function to get coordinates of a given address (Geocoding). What I'm going to do with those coordinates is a different story.

My problem lies with the following code:

jQuery(document).ready(function($) {
  mapObject   = initGoogleMaps();
  coordinates = getCoordinates('United Kingdom');

  console.log(coordinates.toString());

  function initGoogleMaps() {
    google.maps.visualRefresh = true;
    map = new google.maps.Map($("#googleMap")[0], {
      center:            new google.maps.LatLng(51.511214, -0.119824),
      zoom:                     10,
      heading:                  0,
      mapTypeId:                google.maps.MapTypeId.ROADMAP,
      disableDefaultUI:         true,
      disableDoubleClickZoom:   true,
      draggable:                false,
      keyboardShortcuts:        false,
      scrollwheel:              false,
      backgroundColor:          'transparent'
    });
    return map;
  }

  function getCoordinates(address) {
    fallback    = 'London, United Kingdom';
    geocoder    = new google.maps.Geocoder();
    address     = typeof(address) == 'string' ? address : fallback;
    coordinates = '';

    geocoder.geocode({ 'address':address },
                     function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        coordinates = results[0].geometry.location;
      } else {
        coordinates = 'Location: "' + address + '" not found.\n' +
                      'Status: ' + status;
      }
    });

    return coordinates;
  }
}); // jQuery(document)

I'm using Chrome DevTools, more specifically, the Javascript Console built into Google Chrome.

When I refresh the page, the output I get is this:

Coordinates: ↩

I thought maybe the Maps API is unsuccessful in Geocoding the location. But...

  1. That would print a message: Location "London Heathrow" not found.
  2. I declared coordinates outside $.ready() and in the console, after the empty message had been printed, typed coordinates, pressed return and it gave me: coordinates ▸ M {jb: 55.378051, kb: -3.43597299999999, toString: function, b: function, equals: function…}

Which is odd. In my perception, the coordinates identifier has been assigned an empty string ('') value. Why? I called the getCoordinates() function right before I used coordinates identifier.

Could it possibly be that the instructions inside $(document).ready(function(){...}) do not get executed in any particular order? Or is it because of the delay while fetching results through the Maps API? How do I get the console.log(...) instruction only after the value of coordinates has been fetched and assigned?

Maybe it's some stupid mistake I'm overlooking.

Zia Ur Rehman
  • 1,141
  • 2
  • 11
  • 20
  • @geocodezip : I apologize. I kept thinking of it as a problem with jQuery rather than a problem with `geocode`. I did a thorough Google search, I swear. But I think my search terms were entirely wrong. By the way, is there a way to return the results? – Zia Ur Rehman Aug 02 '13 at 23:26
  • As I said in my previous comment `The geocoder is asynchronous, you can **use** the results in the callback function, you can't return them from it.` – geocodezip Aug 02 '13 at 23:31
  • I read that. I thought there would be some other way to return the data, to be used by some other function outside of `getCoordinates()` scope. I gather there isn't. Terribly sorry for appearing to be a dimwit. – Zia Ur Rehman Aug 02 '13 at 23:38

1 Answers1

0

Your coordinates = ''; is out of scope with the .geocode callback function. You need var coordinates = ''; instead.

dfockler
  • 166
  • 4
  • @dfocker I can understand how it can be out of scope. But I don't understand how `var` should solve that problem. I did, however, try that solution anyway. But that doesn't appear to work. – Zia Ur Rehman Aug 02 '13 at 23:22
  • 1
    `var` pulls whatever variable you call it on into the scope of the block it is in. So the `coordinates` variable would be the same variable inside the callback function as outside the callback. But my answer isn't completely right, geocodezip was correct in that it's asynchronous and you can't return the value it gives you. – dfockler Aug 02 '13 at 23:51
  • Regardless of the original question, what you just explained was unknown to me. Maybe out of context, but it helps. Cheers! – Zia Ur Rehman Aug 03 '13 at 00:04
  • I didn't explain it very well, I would recommend looking [here](http://stackoverflow.com/questions/500431/javascript-variable-scope) for more/better info. – dfockler Aug 03 '13 at 00:08