【发布时间】:2020-05-20 17:10:48
【问题描述】:
我有 2 个输入框取货和送货。这是库调用:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=mykey&libraries=places&callback=initMap">
</script>
还有我的自动完成片段:
var inputStart = document.getElementsByClassName('ginput');
for (var i = 0; i < inputStart.length; i++) {
var autocomplete = new google.maps.places.Autocomplete(inputStart[i]);
console.log(autocomplete);
autocomplete.inputId = inputStart[i].id;
autocomplete.bindTo('bounds', map);
autocomplete.setFields(
['address_components', 'geometry', 'icon', 'name']);
var infowindow = new google.maps.InfoWindow();
var infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
console.log(place);
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert("No details available for input: '" + place.name + "'");
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
var address = '';
//console.table(place);
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || ''),
(place.address_components[6] && place.address_components[6].short_name || '')
].join(' ');
}else{
alert("No Place");
}
infowindowContent.children['place-icon'].src = place.icon;
//infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
infowindow.open(map, marker);
HTML:
<b>Pickup:</b>
<div id="pac-container-start">
<input id="pac-input-start" class="ginput" type="text"
placeholder="Enter a pickup location">
</div>
<b>Dropoff:</b>
<div id="pac-container-end">
<input id="pac-input-end" class="ginput" type="text"
placeholder="Enter a dropoff location">
</div>
问题是从下拉列表中选择地址后,我得到一个错误:
scripts.js:159 Uncaught TypeError: Cannot read property 'geometry' of undefined
我已经注销了地方,但它是未定义的,有趣的是当我在第二个框中选择一个地址时,它似乎工作正常。没有错误,绘制出正确的方向等等。 在我看来,它几乎对哪个盒子发送请求感到困惑? 为我指出正确的方向将不胜感激。
【问题讨论】:
-
请提供minimal reproducible example(阅读最小和完整)。
标签: google-maps autocomplete google-places-api