-1

I want to get Latitude and Longitude of a set of addresses.This is the code I used.

var marker_array = [];
//Event detail array
var LiveEventDetails= <?php echo json_encode($liveEventsDetails); ?>;

LiveEventDetails.forEach(function(event) {
geocoder.geocode({ 'address': event.venue }, function (results, status) {
   if (status == google.maps.GeocoderStatus.OK)
    {
    marker_array.push([results[0].geometry.location.A,results[0].geometry.location.F]);
    }
    //1st test
    console.log(marker_array);
  });
  // 2nd test  
  console.log(marker_array);
});
//3rd test  
console.log(marker_array);

the output(marker_array) given by the first console.log() has the pushed data in it.. But after the geocoder function marker_array is shown as empty by the 2nd and third console.log();

How can I keep the pushed array after the geocoder function without being empty..

SNT93
  • 431
  • 1
  • 6
  • 19
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function?](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – geocodezip Jul 24 '15 at 14:10
  • It doesn't happen with other functions..happened with Geocoder function only – SNT93 Jul 24 '15 at 14:12
  • What other functions? Are they asynchronous like the geocoder? – geocodezip Jul 24 '15 at 14:13
  • No In a Synchronous function..Can you give me a solution? – SNT93 Jul 24 '15 at 14:26

1 Answers1

1

I think your issue is that the callback function used by the geocoder, which contains your "test 1", is asynchronous. This means that marker_array is being populated correctly, it is just empty or incomplete when "test 2" and "test 3" run. The true value of marker_array will be the last output from "test 1".

P.S. There is a limit to amount of geocoding uses (source):

The Google Maps API provides a geocoder class for geocoding and reverse geocoding dynamically from user input. When you first load the API, you will be allocated an initial quota of Geocoding requests. Once you have used this quota, additional requests will be rate-limited on a per-second basis. If instead you wish to geocode static, known addresses, see the Geocoding web service documentation.

Xion Dark
  • 3,374
  • 2
  • 15
  • 23