要么我是个白痴,要么这是 Google 地图团队的严重疏忽。
我正在尝试结合标准输入按键事件(当前工作正常)触发按钮单击事件上的位置搜索请求。我梳理了与Google Places 搜索框相关的文档,但没有找到合适的解决方案。
由于保密原因,我使用演示中的示例。
function initialize() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
var input = /** @type {HTMLInputElement} */(document.getElementById('target'));
var searchBox = new google.maps.places.SearchBox(input);
var markers = [];
document.getElementById('button').addEventListener('click', function() {
var places = searchBox.getPlaces();
// places -> undefined
// The assumption is that I could just call getPlaces on searchBox
// but get nothing in 'places'
// Beyond that it doesn't even make a call to the Google Places API
// Currently the only way to perform the search is via pressing enter
// which isn't terribly obvious for the user.
}, false)
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds()
for (var i = 0, place; place = places[i]; i++) {
var image = {
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)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
}