Theses are my marker coordinates.
var markers = [
{
"title": 'Burrel',
"lat": '41.6065764',
"lng": '20.0130826',
},
{
"title": 'Grabian',
"lat": '40.9501',
"lng": '19.583533'
},
{
"title": 'Spac',
"lat": '41.899017',
"lng": '20.0456071'
}
];
and below is my code that does a loop through them all and creates markers on the map as well as adding a click event listener
for (var i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
icon: 'images/marker.png'
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
var x = document.getElementsByClassName("displayblock")[0];
x.style.zIndex=0;
x.className = "w-clearfix slide";
var d = document.getElementById(this.title);
d.className = "w-clearfix slide displayblock";
d.style.zIndex=1;
});
})(marker, data);
}
The original markers that are generated in the loop have an image marker 'images/marker.png' i want to replace this with 'images/marker2.png' when clicked and have them toggled.. a nudge in the right direction would be greatly appreciated..
Try changing the marker icon in the click handler. You just need to keep track of the currently selected marker and reset the others.
marker.setIcon( otherIcon );
https://developers.google.com/maps/documentation/javascript/reference#Marker
setIcon
will work to toggle markers, but the complexity is in adding the event listener and in clearing the non-selected icons in a clean way. In your loop you can add the event listener directly to the marker:
marker.addListener('click', function() {
this.setIcon(selectedSymbol);
});
and you can manage all the markers by adding to an array similar to @tkdave's suggestion:
var markers = [];
function clearSelectedMarker() {
markers.forEach(function(marker) {
marker.setIcon(image);
});
}
for (var i = 0; i < beaches.length; i++) {
var beach = beaches[i];
var marker = new google.maps.Marker({
position: {lat: beach[1], lng: beach[2]},
map: map,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
marker.addListener('click', function() {
clearSelectedMarker();
this.setIcon(selectedSymbol);
});
markers.push(marker);
}
To me this is also more readable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.