2017-02-06 183 views
-1

我有以下功能。在函數參數中設置變量

function geocodePosition(pos, inputField) { 
    var retvalue = ""; 
    geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({latLng: pos}, function (results, status) { 

      if (status == google.maps.GeocoderStatus.OK) { 
       retvalue = results[0].formatted_address; 
       inputField.value = retvalue; 
      } else { 
      alert('Cannot determine address at this location status [' + status + "]"); 
      } 

    }); 
    alert ("retvalue : " + retvalue); 
    return retvalue; 
} 

我知道我錯過了一些基本的東西。但警報聲明中的retvalue總是空白。我如何在調用地理編碼的功能塊中設置它。

親切的問候

邁克爾

+0

的'retvalue'僅適用於'geocoder.geocode({經緯度:POS}回調,功能(結果,狀態){' –

回答

0

這是因爲地理編碼過程是異步。這意味着您的警報在數據存在之前執行。你可以使用這樣的回調函數:

reverseGeocoder: function (lat, lng, callback) { 

    var geocoder = new google.maps.Geocoder; 
    var addressComponents = {}; 
    geocoder.geocode({ 
     'location': { 
      lat:lat, 
      lng: lng 
     } 
    }, function (results, status){ 
     if(status === google.maps.GeocoderStatus.OK){ 

       callback(results); 
      } else { 
       alert('No information found.'); 
      } 

     }else { 
      alert("Error "+status); 
     } 
    }); 

用法:

doGeocode (lat, lng, function (response){ 
//here are your data 
)}; 
+0

非常感謝,我修改了代碼以便將MapMarker傳遞給函數reversegeocode,並使用地理編碼結果設置標記的標題。 – mbieren