Reputation: 284
I need to change the icon displayed by a Google Maps marker programmatically in client-side javascript, after the map has been rendered. Is there a way to achieve this?
I have a webpage containing 32 markers, and I need to be able to change the icons for some of these when I receive a message over a websocket connection. I would hope to be able to use getElementById to access the relevant DOM element. I have tried setting an id within the marker initialisation closure but this id is not found by getElementById.
EDIT This code from my original question does not work.
var marker_02 = new google.maps.Marker({
position: {lat: 51.12345, lng:-0.12345},
map: map,
icon: "purple_icon.png",
title: "02",
url: "02.html",
id: "marker_02"
});
google.maps.event.addListener(marker_02, "click", function() {
window.location.href = this.url;
});
var addr = "ws://192.168.12.247:8080/ws";
var websocket = new WebSocket( addr);
websocket.onmessage = function(e){
var message = e.data;
console.log("message received:" + message);
if (message == "alarm") {
document.getElementById("marker_02").icon = "red_icon.png";
}
}
EDIT - the final solution after concluding that the only way to change the marker icon dynamically is to remove it and make a new one with the new settings...
var addr = "ws://192.168.12.247:8080/ws";
var websocket = new WebSocket( addr );
websocket.onmessage = function(e){
var message = e.data;
//console.log("message received:" + message);
if (message == "alarm_02") {
console.log("received alarm_02");
// Remove marker by setting Map to null:
marker_02.setMap(null);
// Create new red marker:
marker_02 = new google.maps.Marker({
position: {lat: 51.12345, lng:-0.12345},
map: map,
icon: "red_icon.png",
title: "02",
url: "02.html"
});
};
};
Upvotes: 0
Views: 1022
Reputation: 338
I dont know if it really is what you need but I'm going to try to help you. Think that each of the markers is an object with its attributes, which one of them refers to the file that gives shape to the icon of the marker in question, simply every time you create a marker you must indicate which file you want to be the one that shapes the marker. With this in mind, you should know that getElementById does not work because the object simply does not have an id. To change it you should do the following:
websocket.onmessage = function(e){
var message = e.data;
console.log("message received:" + message);
if (message == "alarm") {
marker_02.icon = "red_icon.png";
}
}
Upvotes: 1