0

I have a function like this

function geokod(district){
var c= new Array();
      //declare geocoder
      var geocoder = new google.maps.Geocoder();
         geocoder.geocode( { 'address': district}, function(results, status) {

              if (status == google.maps.GeocoderStatus.OK) {
                 //c.push(results[0].geometry.location.lat());
                 //c.push(results[0].geometry.location.lng());
              c[0]=results[0].geometry.location.lat();
              c[1]=results[0].geometry.location.lng();

              }  //endif

            });

    return c;

    }

I call this function like this

var loc = new Array();
loc = geokod('Kuala Lumpur, Malaysia');

I try to test it

console.log(loc.length) //failed to get the length, output 0
console.log(loc) //success, output the coordinate

I try to assign it to other array like this

var location = ["Kuantan",0.0,0.0];
location[1] = loc[0];
location[2] = loc[1];

The array location[1] and [2] content undefined value.

I am a bit confuse why this happen. Please help, Thank you.

--- After some suggestions and do some homework i alter code above to this ---

function foo(address, fn){
        var c= new Array();

  //declare geocoder
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address}, function(results, status) {

          if (status == google.maps.GeocoderStatus.OK) {
          c[0]=results[0].geometry.location.lat();
          c[1]=results[0].geometry.location.lng();

          fn(c); 

          }  //endif

  });
}

And my callback

foo(locations[i][0], function(lokasi){
    alert(lokasi[0]); // this will alarm content
    loc = lokasi; // this not assign the content
  });

Still not solve my how to assign the return value to the new var.

rajalanun
  • 27
  • 5
  • Is it because "location" is a reserved javascript variable for accessing properties of the URL you're on? – Joshua Terrill Jul 11 '17 at 02:41
  • 1
    You're not waiting until you get the response from the geocode before you're returning `c`. You need to return `c` as a **callback** from the geocode service. – Obsidian Age Jul 11 '17 at 02:45

0 Answers0