-1

google map api is loaded asynchroneously

   jQuery(function($) {
    // Asynchronously Load the map API 
    var script = document.createElement('script');
   script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
        document.body.appendChild(script);
});

i then do

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);



    var address ="Marseille";

   var geocoder;
   geocoder = new google.maps.Geocoder();
   var markers;
    markers=  geocoder.geocode( { 'address': address}, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {               
               var titlelatlong=[address,results[0].geometry.location.lat(),results[0].geometry.location.lng()];                    
              console.log(titlelatlong);    
              return titlelatlong;
             }
      }); 

       console.log(markers);

why

 console.log(titlelatlong)

output is what i want and

console.log(markers) 

is undefined ?

how can i fix this ?

Matoeil
  • 6,851
  • 11
  • 54
  • 77

2 Answers2

1

geocoder.geocode() is an asynchronous function, while your javascript executes synchronously.

The asynchronous function geocoder.geocode() will be called, and then your console.log(markers) will be executed, whether or not the previous asynchronous function has finished or not.

Either, assign the variable value in your callback, or use a promise library to wrap your asynchronous code to make it behave like synchronous code.

var markers;
geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {               
        var titlelatlong=[address,results[0].geometry.location.lat(),results[0].geometry.location.lng()];                    
        markers = titlelatlong; //assign value to variable
        console.log(markers);
    }
}); 
Daniel B
  • 8,770
  • 5
  • 43
  • 76
1

The Google Maps Geocoding API is asynchronous, which means that assigning marker to geocoder.geocode() will be undefined since the method itself returns nothing.

What geocoder.geocode() provides is to consume a callback function which it will call once it finishes running. The Geocoding API will pass data to the callback that you defined, and from there you can obtain the information you need, like the console.log(titlelatlong) you printed out.

Griffith
  • 3,229
  • 1
  • 17
  • 30