【发布时间】:2016-02-06 03:55:56
【问题描述】:
我严格按照 Google 开发者documentation 实现了一个地方搜索框。标记将根据特定的搜索词(例如“餐厅”)显示在地图上。当然,我想在用户单击标记时显示一个信息窗口,以实际向用户提供有关该地点的一些信息。我已关注 Google 开发人员 documentation 以激活 infowindows,但没有任何成功(我在代码中所做的更改由 cmets 1、2 和 3 说明)。
这里之前的帖子也没有帮助我。任何帮助将不胜感激。
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
// 1: Variables infowindow and service:
var infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
var markers = [];
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
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)
};
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
// 2: getDetails, referring to the "places" (var places = searchBox.getPlaces();) already on the map
// 3: addlistener on the markers, to show an infowindow upon a clickevent
service.getDetails(places, function(place, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
google.maps.event.addListener(markers, 'click', function() {
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
'Place ID: ' + place.place_id + '<br>' +
place.formatted_address + '</div>');
infowindow.open(map, this);
});
}
});
map.fitBounds(bounds);
});
}
</script>
【问题讨论】:
标签: javascript google-maps-api-3