請幫助,我真的很困惑添加事件點擊標記後成功的搜索地點在谷歌地圖上。我試圖在一些項目添加事件點擊標記和工作,但不使用方法搜索地方,這意味着使用硬編碼標記位置,對於這種情況下,我希望有人可以幫助我,這是我的代碼。如何添加事件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);
}
});
}
感謝您回答我已經嘗試解決我的問題,並得到解決方案僅適用於標記添加索引循環 –