我有一个简单的星期四到星期日按钮布局,我希望能够根据按下的按钮添加标记(并随后删除它们)。如果按下星期五,它将删除现有标记(如果有)并添加与星期五相关的数据。这是我的代码:
function initialize() {
var mapOptions = {
zoom: 12,
center: newYork,
disableDefaultUI: true,
mapTypeControlOptions: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function loadMarkers(val) {
marker = new google.maps.Marker({
position: val,
map: map,
title: "Hi there!"
});
}
$(document).ready(function() {
google.maps.event.addDomListener(window, 'load', initialize);
$('#thurs').on('click', function() {
if(!marker) {
loadMarkers(newYork);
console.log(marker);
}
else if(marker) {
marker.setMap(null);
}
});
})
首次点击,添加标记;第二次单击将删除标记,但后续单击不执行任何操作。
答案 0 :(得分:0)
如果您想切换标记,则需要检查:
$('#thurs').on('click', function() {
if(!marker || (marker.getMap() == null)) {
loadMarkers(newYork);
console.log(marker);
}
else if(marker && (marker.getMap() != null)) {
marker.setMap(null);
}
});
代码段:
var newYork = {
lat: 40.7127837,
lng: -74.0059413
};
var marker, map;
function initialize() {
// New York, NY, USA (40.7127837, -74.00594130000002)
var mapOptions = {
zoom: 12,
center: newYork,
disableDefaultUI: true,
mapTypeControlOptions: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function loadMarkers(val) {
marker = new google.maps.Marker({
position: val,
map: map,
title: "Hi there!"
});
}
$(document).ready(function() {
google.maps.event.addDomListener(window, 'load', initialize);
$('#thurs').on('click', function() {
if (!marker || (marker.getMap() == null)) {
loadMarkers(newYork);
console.log(marker);
} else if (marker && (marker.getMap() != null)) {
marker.setMap(null);
}
});
})

html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="thurs" type="button" value="Thurs" />
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>
&#13;