根据我想显示或隐藏标记标签的缩放级别,我在这里查看了答案,虽然我对我要做什么有了更好的了解,但我没有任何运气能够将其实施到我的谷歌地图中。 仅当缩放级别为>7 时,才应显示标签。
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 52.024, lng: 2.887}
});
setMarkers(map);
}
var tasks = [
['Marker 1', 32.89, 12.25, 78],
['Marker 2', 60.29, -4.29, 83],
['Marker 3', 57.39, 1.5, 85],
['Marker 4', 52.50, 4, 94]
];
function setMarkers(map) {
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var marker = new google.maps.Marker({
position: {lat: task[1], lng: task[2]},
map: map,
title: task[0],
label: task[0],
url: "somesite?ID=" + task[3]
});
marker.addListener('click', function() {
window.location.href = this.url;
});
}
}
将标记的引用保存在数组中。 在地图上创建一个"zoom_changed"侦听器,当它执行时,如果缩放为 <= 7,则通过隐藏标签(将其设置为 null(的标记数组进行处理,如果缩放> 7,则显示标签(将其设置为等于标题(。
map.addListener('zoom_changed', function() {
for (var i=0; i< gmarkers.length; i++) {
if (map.getZoom() > 7) {
gmarkers[i].setLabel(gmarkers[i].getTitle());
} else {
gmarkers[i].setLabel(null);
}
}
});
概念验证小提琴
代码片段:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 52.024,
lng: 2.887
}
});
setMarkers(map);
map.addListener('zoom_changed', function() {
for (var i = 0; i < gmarkers.length; i++) {
if (map.getZoom() > 7) {
gmarkers[i].setLabel(gmarkers[i].getTitle());
} else {
gmarkers[i].setLabel(null);
}
}
});
}
var tasks = [
['Marker 1', 32.89, 12.25, 78],
['Marker 2', 60.29, -4.29, 83],
['Marker 3', 57.39, 1.5, 85],
['Marker 4', 52.50, 4, 94]
];
var gmarkers = [];
function setMarkers(map) {
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var marker = new google.maps.Marker({
position: {
lat: task[1],
lng: task[2]
},
map: map,
title: task[0],
url: "somesite?ID=" + task[3]
});
gmarkers.push(marker);
marker.addListener('click', function() {
window.location.href = this.url;
});
}
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0px;
margin: 0px;
background-color: white;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id='map'></div>