【发布时间】:2017-01-19 22:00:56
【问题描述】:
自动填充搜索功能在我的地图上运行良好,可以放大搜索到的地址并将自定义大头针居中放置,但大头针在所有缩放级别都保持在那里。我的目标是当用户缩小超过 18 级缩放时移除/隐藏图钉。我的猜测是带有“zoom_changed”的 google.maps.event.addListener 可能会起作用,但我不知道在哪里或如何将它放在这段代码中。提前感谢您的帮助。
// 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 markersS = [];
// 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 markersS.
markersS.forEach(function(marker) {
marker.setMap(null);
});
markersS = [];
// 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: '.../HOME.png',
anchor: new google.maps.Point(41.5, 64),
};
// Create a marker for each place and also set Zoom Condition.
google.maps.event.addListener(map, 'zoom_changed', function() {
var zoomS = map.getZoom();
if (zoomS>=18) {
markersS.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location,
//animation: google.maps.Animation.DROP
}));
}
else if (zoomS<18) {
markersS.forEach(function(marker) {
marker.setMap(null);
});
markersS = [];
}
});
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
【问题讨论】:
-
添加 IF、IF ELSE 功能现在一切正常,但是现在当我搜索新地址时,主页图标标记了新地址,但旧搜索的主页图标仍然存在,显示两个图标,这继续前进。有什么我可以添加到代码中来删除以前搜索的图标并只加载新的/当前的吗?
标签: javascript google-maps google-maps-api-3 google-maps-markers