2

I have three addresses saved in a database, I’m outputting them and retrieving the values with jQuery. However, the console only displays the third field with the longitude and latitude.

I have tried to use while function to get the three addresses and use console.log(i) to show the value of i, but it only shows the third one.

PHP:

<?php $count = 0?>
<?php foreach($get_address as $get) {?>
<?php $count += 1;?>
<input type="text" id="address_<?=$count?>" value="<?=$get->address?>">
<input type="text" id="latitude_<?=$count?>">
<input type="text" id="longitude_<?=$count?>"><br>
<?php } ?>
<input type="hidden" id="count_address" value="<?=$count_address->count_address?>"><br>

JavaScript:

function getCoor(){
    var count = 3;
    var i = 1;
while(true){

var geocoder = new google.maps.Geocoder();
var address = $("#address_"+i).val();

geocoder.geocode( { 'address': address}, function(results, status) {

if (status == google.maps.GeocoderStatus.OK) {
 var latitude = results[0].geometry.location.lat();
 var longitude = results[0].geometry.location.lng();
 $("#latitude_"+i).val(latitude);
 $("#longitude_"+i).val(longitude);
 console.log(i);

      } 
});

    if(count == i){
        break;
    }
     i += 1;
    }

}
Liam Newmarch
  • 3,935
  • 3
  • 32
  • 46
Tristan Ross
  • 117
  • 1
  • 9
  • Please go read [ask]. You need to explain to us what your specific _problem_ is, not just what you “want”. You got multiple fields with ids containing an “index” at the end here, so … loop over them then? – 04FS Jun 26 '19 at 08:41

1 Answers1

0

It is because geocoder.geocode is an asynchronous call.

Read more about let here

Refer here the issue you are facing.

Try the code below.

function getCoor(){
  let count = 3;

  for (let i = 1; i < count; i++) {
    let geocoder = new google.maps.Geocoder();
    let address = $("#address_"+i).val();

    geocoder.geocode( { 'address': address}, function(results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
         let latitude = results[0].geometry.location.lat();
         let longitude = results[0].geometry.location.lng();
         $("#latitude_"+i).val(latitude);
         $("#longitude_"+i).val(longitude);
         console.log(i);
      } 
    });
  }
}
bijoshtj
  • 299
  • 4
  • 14