2016-03-20 17 views
-1

我有一個用戶輸入他的位置的輸入。從這個位置,我想獲取城市,州和郵政編碼,並將這些信息輸入到其他輸入(城市,州和郵政的輸入)中,因此用戶不需要手動填寫這些信息。Google自動完成 - 如何獲取有關加載地址的信息?

我找到了一個我試圖實現的例子here,並試圖根據我的需要進行修改。

所以我來到這裏:

var placeSearch, autocomplete_origin_address, autocomplete_destination_address; 
var componentForm_origin = { 
    user_origin_city: 'user_origin_city', 
    user_origin_state: 'user_origin_state', 
    user_origin_zip: 'user_origin_zip' 
}; 

function initAutocomplete() { 
    console.log('in "initAutocomplete"'); 
    autocomplete_origin_address = new google.maps.places.Autocomplete(
    document.getElementById('user_origin_address'), 
          types: ['geocode']} 
); 
    autocomplete_origin_address.addListener("place_changed", 
             fillInAddress(autocomplete_origin_address, 
                 "user_origin_address", 
                 "user_origin_city", 
                 "user_origin_state", 
                 "user_origin_zip")); 

} 

function fillInAddress(autocomplete_resource, address, city, state, zip) { 
    console.log("! !x"); 
    // Get the place details from the autocomplete object. 
    var place = autocomplete_resource.getPlace(); 

    // origin fields to populate with the selected address 
    var fetched_street_number = fetchAddressDetails(place, "street_number", "long_name"); 

    var fetched_address = fetchAddressDetails(place, "route", "long_name"); 
    $("#"+address).val(fetched_street_number + " " + address); 

    var fetched_city = fetchAddressDetails(place, "locality", "long_name"); 
    $("#"+city).val(fetched_city); 

    var fetched_state = fetchAddressDetails(place, "administrative_area_level_1", "short_name"); 
    $("#"+state).val(fetched_state); 

    var fetched_zip = fetchAddressDetails(place, "postal_code", "long_name"); 
    $("#"+zip).val(fetched_zip); 
} 

function fetchAddressDetails(autocomplete_place, detail_type, name_type){ 
    console.log("in fetchAddressDetails"); 
    var item = $.grep(autocomplete_place.address_components, 
        function(e){ return e.types[0] == detail_type; }); 
    var item_data = item[0][name_type]; 
    console.log("item_data: "+item_data); 
    return item_data;              
} 

initAutocomplete(); 

但是當我加載頁面時,我得到這個錯誤:

in "initAutocomplete" 
! !x 
in fetchAddressDetails 
Uncaught TypeError: Cannot read property 'address_components' of undefined 

我想谷歌的問題,但不能擺脫它,使它的代碼工作。 我一般都在嘗試 - 我在頁面上有4個輸入,用戶輸入地址。 所以我想 - 當輸入這4個輸入中的每一個的地址 - ruby​​ google自動完成功能,獲取地址並將城市/州/郵政信息輸入到相應的輸入。

請問您能提醒一下,爲什麼它目前不能提取任何東西?

預先感謝您。

+0

請提供[最小的,完整的,測試和可讀示例](http://stackoverflow.com/help/mcve),它演示了您的問題,包括任何必需的HTML/CSS。 – geocodezip

回答

0

也許只是一個錯字,但有可能會造成問題的一個語法錯誤...

types: ['geocode']} // <~~ missing it's opening curly brace..! 

應該讀...

{types: ['geocode']} 
+0

感謝評論@Billy,這只是一個錯字(當我在這裏格式化代碼時發生)。 – user984621

相關問題