请帮助,我真的很困惑添加事件点击标记后成功的搜索地点在谷歌地图上。我试图在一些项目添加事件点击标记和工作,但不使用方法搜索地方,这意味着使用硬编码标记位置,对于这种情况下,我希望有人可以帮助我,这是我的代码。如何添加事件addListener点击标记后搜索地点谷歌地图
function initMap() {
var mapOptions = {
center: new google.maps.LatLng(0.7893, 113.9213),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
var input = document.getElementById('search_location_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());
});
// marker
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;
}
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
for (var i = 0; i < markers.length; i++) {
var data = markers[i];
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
console.log(data.title);
});
})(markers, data);
}
});
}
感谢您回答我已经尝试解决我的问题,并得到解决方案仅适用于标记添加索引循环 –