我需要在执行搜索后显示Google地图,但搜索框应该包含自动填充位置/地点。搜索框应该在搜索时具有自动填充位置,当单击时,应该相应地显示地图。
以下是代码:
<script>
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key
&libraries=places&callback=initAutocomplete"
async defer></script>
这是另一个代码:
<input id="pac-input" class="controls" type="text" placeholder="Search" >
<div id="map"></div>
答案 0 :(得分:1)
一种方法是将CSS中visibility
元素的<div id="map"></div>
属性设置为hidden
。
#map {
height: 100%;
visibility: hidden;
}
然后,在搜索框places_changed
事件处理程序的末尾,将地图元素的visibility
设置为visible
:
document.getElementById('map').style.visibility = 'visible';
另外,为了防止搜索框也不可见,我会从你的代码中删除这一行:
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
以下是a JSBin的工作示例。