如果这已经发布了,我很抱歉,但我花了至少一个小时试图找到合适的最新解决方案。
我可以设置自定义标记图像,但无法为正常和单击状态设置不同的标记图像。我找到了。这是我正在使用的代码
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: center
});
var infowindow = new google.maps.InfoWindow({});
var marker, count;
for (count = 0; count < locations.length; count++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[count][1], locations[count][2]),
map: map,
title: locations[count][0],
icon: image
});
marker.addListener("click", () => {
marker.setIcon("/wp-content/uploads/2020/07/Selected.svg");
});
google.maps.event.addListener(marker, 'click', (function(marker, count) {
return function() {
infowindow.setContent(locations[count][0]);
infowindow.open(map, marker);
}
})(marker, count));
}
}
此部分会在单击时更改标记图标,但仅针对第一个,并且在单击其他标记时不会更改为未选择的图标。
marker.addListener("click", () => {
marker.setIcon("/wp-content/uploads/2020/07/Selected.svg");
});
尝试将setIcon
放入google.maps.event.addListener
中
例如
google.maps.event.addListener(marker, 'click', function() {
return function() {
marker.setIcon("/wp-content/uploads/2020/07/Selected.svg");
}
});
最终我弄明白了。这是工作代码。我得到了列出位置的PHP部分,但这足以回答这个问题。
var markers = [];
var normalIcon = '/wp-content/uploads/2020/07/Pin.svg';
var activeIcon = '/wp-content/uploads/2020/07/Selected.svg';
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: center
});
var infowindow = new google.maps.InfoWindow({});
var marker, count;
for (count = 0; count < locations.length; count++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[count][1], locations[count][2]),
map: map,
title: locations[count][0],
icon: normalIcon
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, count) {
return function() {
for (var j = 0; j < markers.length; j++) {
markers[j].setIcon(normalIcon);
}
this.setIcon(activeIcon);
infowindow.setContent(locations[count][0]);
infowindow.open(map, marker);
}
})(marker, count));
}