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.
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.
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();