Search code examples
javascriptjquerygoogle-mapsgoogle-maps-api-3google-geocoder

using google map geocoder.geocode before initializing the map


I have created a nice Google map form that gets clients data from the database ( with a jQuery post call to php) and loads it into the clients_details. if clients_details[]['location'] which is Latlng is provided in the database all works well and marker gets displayed as expected. Problem is that when clients_details[]['location'] is not provided then I use the address from clients_details[]['address'] and try to get position of the marker by using geocoder.geocode. However surprisingly every time the code gets to the geocoder it jumps from it and comes back to it after it initialized the map ! so markers wont get added to the map !

I am assuming it has something to do with JavaScript function priorities but not sure how

<script>
var clients_details // getting this from database;
var infowindow =[];
var geocoder;
var map;
 function showMarkers(clients_details)
 {

   var marker = [];
   for (var i = 0; i < clients_details.length; i++)
   {

       content = 'Test Content' ;
       infowindow[i] = new google.maps.InfoWindow({
           content: content,
           maxWidth: 350
       });           

       var client_location;
       if (clients_details[i]['location'] !== null)
       {
       // Geting Lat and Lng from the database string
       LatLng = clients_details[i]['location'];           
       client_location = new google.maps.LatLng (LatLng);           
       }
       else
       {            
         client_address = clients_details[i]['address'];
         geocoder.geocode(
           { 'address': client_address},
           function(results, status)
           {                 
             if (status == google.maps.GeocoderStatus.OK)
             {
               client_location = results[0].geometry.location;
             }
             else
               alert('Geocode was not successful for the following\n\
                      reason: ' + clients_details[i]['name']+'\n' + status);
           });

         }
         marker[i] = new google.maps.Marker({
           position: client_location,
           map: map,               
           title: clients_details[i]['name']
       });


       // Add 'click' event listener to the marker
       addListenerMarkerList(infowindow[i], map, marker[i]);

   }// for
 }// function


Solution

  • The

    marker[i] = new google.maps.Marker({
           position: client_location,
           map: map,               
           title: clients_details[i]['name']
    });
    

    Code should be inside the callback in the geocoder.geocode call. Because in your code the client_location is computed after the marker[i]. What you could do is:

    compute the client_location and when the client_locolation is computed
    then compute the marker[i]
    

    So your code could be like this:

    // ... your code as is
    geocoder.geocode(
        { 'address': client_address},
        function(results, status)
        {                 
            if (status == google.maps.GeocoderStatus.OK)
            {
                client_location = results[0].geometry.location;
    
                // closure needed, for the marker[i] to work correctly, 
                // because we are in a loop on i
                (function (i) {
                    marker[i] = new google.maps.Marker({
                        position: client_location,
                        map: map,               
                        title: clients_details[i]['name']
                    });
                })(i);
    
            }
            else
            {
                alert('Geocode was not successful for the following\n\
                      reason: ' + clients_details[i]['name']+'\n' + status);
            }
        }
    );
    // .... your code as is