2012-12-18 23 views
4

我有下面的JavaScript代碼,這是谷歌地圖自動完成不同的輸入文本框是地址的一部分。更改谷歌地圖自動完成的文本框中的值

function startAutoComplete() { 
    var address = document.getElementById("addressId"); 
    var city = document.getElementById("cityId"); 
    var state = document.getElementById("stateId"); 
    var zip = document.getElementById("zipId"); 

    //option for autocomplete 
    var option = {types: ['geocode'], componentRestrictions: {country: 'us'}}; 

    //autocomplete for address textbox 
    autocomplete = new google.maps.places.Autocomplete(address, option); 

    google.maps.event.addListener(autocomplete, 'place_changed', function() { 
     var place = autocomplete.getPlace(); 

     //parses the result object and populates the other textboxes accordingly 
     for(i=0; i<place.address_components.length; i++) 
     { 
      if(place.address_components[i].types[0] == 'locality') 
      city.value = place.address_components[i].long_name; 

      if(place.address_components[i].types[0] == 'administrative_area_level_1') 
      state.value = place.address_components[i].short_name; 

      if(place.address_components[i].types[0] == 'postal_code') 
      zip.value = place.address_components[i].long_name; 
     } 

     /* Here is the PROBLEM */ 
     address.value = place.name; 

    }); 

然而,當我嘗試更新正在汽車用完整的地址(所以這裏只是門牌號和街名)的縮寫形式完成文本框。完整地址文本框中的值不會更改。我試過使用jquery,並在文本框中使用setAttribute()設置value屬性。我究竟做錯了什麼?

+0

您能否顯示您的選項對象,您用來初始化自動填充的對象? 'autocomplete = new google.maps.places.Autocomplete(address,option);' – ElHacker

+0

[只顯示google.maps.event.addListener()中的街道地址)的可能重複(http://stackoverflow.com/questions/ 13524258/show-just-the-street-address-in-google-maps-event-addlistener) –

+0

添加了用於自動完成的選項變量。 – PleaseWork

回答

0

我發現了一個非常臨時的解決方案。看起來,如果您故意創建錯誤,它會從原始文本框中解除Google地圖自動完成的綁定,並使用更新的值顯示您的原始文本框。不是一個真正的解決方案,但它是一個開始

//Created this variable that stores the pac-container 
var element = document.getElementsByClassName("pac-container"); 

//inside the addListener() function I added this to create a DOM error 
element[0].childNodes[0].childNodes[0].removeChild(); 

的JavaScript拋出一個錯誤,但它至少可以讓我把在我想要的東西在文本框中使用「.value的」

同樣不是一個解決方案,但一開始。我希望我們找到更好的解決方案。

0

如何克隆元素,然後用相同的替換,然後再次調用initialze。

好吧,這樣的事情。這在過去對我有效。

$("#Id").replaceWith($("#Id").clone()); 
initialize(); 

這裏initailize是當DOM負載google.maps.event.addDomListener(窗口, '負載',初始化),其被調用的方法;在你的情況下它可能不同

1

自動完成對象有幾個不明顯的事件監聽器。實際情況是,當你運行你的代碼時,它實際上確實會改變它的值,然後Autocomplete對象將它變回真快!要測試這個,請在​​address.value = place.name;行後面加上alert();。如果您添加一個setTimeout(),並將延遲值設置爲1ms,那麼您可以調整它以保持您的價值。但是,當您離開該字段時,自動填充的blur事件觸發器將再次覆蓋您的地址。你可以解決這個問題有一個行:

address.addEventListener('blur', function() { address.value = place.name; });

這需要照顧的第一例一樣,所以你甚至不會需要添加一個setTimeout()。用這個事件監聽器代替你設置該值的行,並且它將代替Autocomplete的回調函數,該函數在每次觸發時設置文本。

相關問題