谷歌地图api地方自动完成getPlace()不工作

问题描述:

我有谷歌地图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

原因是Google使用了另一个标识符'地点'而不是通常的'名称'。

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

代码:

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

Example