2013-05-13 130 views
0

我有谷歌地圖api地方自動完成的問題。看來,函數getPlaces()如文檔中所述不工作: Autocomplete谷歌地圖api地方自動完成getPlace()不工作

Returns the details of the Place selected by user if the details were successfully retrieved. Otherwise returns a stub Place object, with the name property set to the current value of the input field.

以一個下面的代碼作爲示例:

<html> 
<head> 
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&libraries=places"></script> 
    <script type="text/javascript"> 
    initialize = function() { 
     var input = document.getElementById('locationsearch'); 
     var options = { 
      types: ['(cities)'] 
     }; 
     autocomplete = new google.maps.places.Autocomplete(input, options); 
    } 
    google.maps.event.addDomListener(window, 'load', initialize); 
    submitform = function() { 
     searchplace = autocomplete.getPlace(); 
     console.log(searchplace.name); 
    } 
    </script> 
</head> 
<body> 
    <form onsubmit="submitform();return false;"> 
     <input type="text" id="locationsearch"/> 
     <input type="button" value="search" onclick="submitform(); return false;"/> 
    </form> 
</body> 
</html> 

這個簡單的代碼使用自動填充功能在input="text"元件和後按鈕旁邊的它被按下它應該在控制檯中記錄地名。 問題我有當input元素有不完整的地方選擇。我期望getPlace()函數返回place對象的名稱屬性設置爲當前值input元素。相反,控制檯正在記錄錯誤: Uncaught TypeError: Cannot read property 'name' of undefined

有沒有什麼我做錯了使用地方自動完成或是這個功能只是無法正常工作? 謝謝。

+0

請定義 – 2013-05-13 22:53:26

+0

「選擇不完整的地方」,當你寫幾個字母到輸入元素,你不接從自動完成列表什麼這是。位置不被選擇,但輸入元素也不是空的。 – Ogrim 2013-05-14 08:06:47

+0

該文檔僅針對在輸入中按下輸入鍵的情況描述了此行爲。 – 2013-05-14 10:43:47

回答

0

原因是Google使用了另一個標識符'地點'而不是通常的'名稱'。

所以,如果你使用'place'的子元素'locality',你可以得到這個地方的名字。

代碼:

var val = place.address_components[0][componentForm['locality']]; 

Example

相關問題