-1

enter image description here

I was trying to push the latitude and longitude into co (array), but at the bottom when I displayed the length of co, it was 0.

If I replace co.push(latitude,longitude) with alert(latitude) it works fine.

31piy
  • 23,323
  • 6
  • 47
  • 67
Recker
  • 3
  • 1
  • 1
    Post code, not images. See [*How to create a minimal, complete and verifiable example*](https://stackoverflow.com/help/mcve). – RobG Jan 05 '18 at 05:30

1 Answers1

0

First of all,

I am not quite sure if you really want to push the values like that

co.push(latitude,longitude)

This will be ended up something like this.

[latitude,longitude,latitude,longitude,latitude,longitude]  

Instead, you can make an object and push them like

[{lat:"",lan:""},{lat:"",lan:""},{lat:"",lan:""}]

Secondly, geocoder.geocode method works asynchronously
so by the time your alert function is invoked, your geocodes are not available yet.
That's why it shows length 0

There are many ways to solve the issues, callback, promise , generator and async/await

I will re-write your code using promise here

function getCode() {

let geocoder = new google.maps.Geocoder();
let promises = [];

for(let i=0,arr=["melbounre","south bank","kew"];i<3;i++){
 promises.push(resolveGeocode(geocoder,arr[i]));
}

 Promise.all(promises).then(function(values){

  // array of geocodes available here

  alert(values[0].lat);
  alert(values[0].lng);

  alert(values[1].lat);
  alert(values[1].lng);

  alert(values[2].lat);
  alert(values[2].lng);
 })  

};

function resolveGeocode(geocoder,address){
return new Promise(function(resolve,reject){
  geocoder.geocode( {'address':address}, function( results, status ) {
      if(status == google.maps.GeocoderStatus.OK){
         resolve({
          lat:results[0].geometry.location.lat(),
          lng:results[0].geometry.location.lng()
         });
      }  

  });
})
}

getCode();
Mia
  • 184
  • 5