我正在使用一个自定义按钮,该按钮会将标记从查询切换到Google地方信息库。我正在对Google地方使用两个查询,分别是学校和公园。我只是想切换标记,而不是始终显示它们,以免使用户混乱。我知道我缺少一种清除结果的方法,但是我不知道如何使用事件监听器来实现。
有人可以帮助我通过事件监听器切换标记吗?
这里是Demo
function parkControl(parkcontrolDiv, map) {
// Set CSS for the control border.
var parkbuttonUI = document.createElement('div');
parkbuttonUI.style.backgroundColor = '#fff';
parkbuttonUI.style.border = '2px solid #fff';
parkbuttonUI.style.borderRadius = '3px';
parkbuttonUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
parkbuttonUI.style.cursor = 'pointer';
parkbuttonUI.style.marginBottom = '15px';
parkbuttonUI.style.marginRight = '10px';
parkbuttonUI.style.padding = '10px 14px';
parkbuttonUI.style.textAlign = 'center';
parkbuttonUI.title = 'Click to show Parks';
parkcontrolDiv.appendChild(parkbuttonUI);
// Set CSS for the control interior.
var parkControlText = document.createElement('div');
parkControlText.style.color = 'rgb(25,25,25)';
parkControlText.style.fontSize = '18px';
parkControlText.style.fontFamily = 'Fontawesome';
parkControlText.innerHTML = '<i class="fas fa-tree"></i>';
parkbuttonUI.appendChild(parkControlText);
parkbuttonUI.addEventListener('click', function() {
if(marker == null){
map.setZoom(11);
var center = {lat: 38.823327, lng: -76.984026 };
var request = {
location: center,
radius: 8046,
types: ['park'],
};
//Get Results
function callback(results, status) {
if(status == google.maps.places.PlacesServiceStatus.OK){
for(var i = 0; i < results.length; i++){
createMarker(results[i]);
}
}
}
//Add Marker
var marker;
var placesMarker = [];
var image = {
url: "/images/GoogleMaps/Pins/parks.png",
scaledSize: new google.maps.Size(30, 30), // scaled size
};
function createMarker(place) {
var placeLoc = place.geometry.location;
marker = new google.maps.Marker ({
map:map,
icon:image,
position: place.geometry.location,
id: place.place_id
});
placesMarker.push(marker);
console.log(marker);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(placesMarker, 'click', function() {
infowindow.setContent(place.name + '<br />' + place.rating);
infowindow.open(map,this);
});
}
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
service.getDetails(request, callback);
} else {
marker.setMap(null);
}
});
};
var parkcontrolDiv = document.createElement('div');
var customControl = new parkControl(parkcontrolDiv, map);
parkcontrolDiv.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(parkcontrolDiv);