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...
- That would print a message:
Location "London Heathrow" not found.
- I declared
coordinates
outside$.ready()
and in the console, after the empty message had been printed, typedcoordinates
, 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.