Saving geocoder results to an array - Closure Trouble

后端 未结 1 1807
臣服心动
臣服心动 2020-12-07 04:50

Okay, so I have searched a while for a solution to this problem, but I have found nothing specifically on this. And before you point me to Google\'s Terms of Service, pleas

相关标签:
1条回答
  • 2020-12-07 05:49

    This is a FAQ. Geocoding is asynchronous. You need to save the results in the callback function which runs when they are returned from the server.

    Something like (not tested)

    Updated to use function closure

    function geocodeAddress(address, i) {
      geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
           var latLong = results[0].geometry.location;
           coordinates = latLong.lat() + "," + latLong.lng();
           adressdaten[i][6] = coordinates;
        } else {
           alert('Geocode of '+address+' was not successful for the following reason: ' + status);
        }
      });
    }
    
    var geocoder = new google.maps.Geocoder();
    for (i=1; i<adressdaten.length-1; i++)  {
      //Save array-data in String to pass to the Geocoder
      var adresse = adressdaten[i][3] + " " + adressdaten[i][4];
      var coordinates;
      geocodeAddress(addresse, i); 
    

    }

    0 讨论(0)
提交回复
热议问题