I managed to get the location of several buses from a public transport company here in Brazil. I managed to send via websocket and plot on google maps. Everything works perfectly except that the old marks keep showing up on the maps. Could anyone help me to delete them after changing their locations?
Thank you very much in advance.
<script>
function setMarkers(map) {
var ws = new WebSocket('ws://localhost:8000/ws/bus/');
ws.onmessage = function(e){
var data = JSON.parse(e.data);
for (let i=0; i<data.length; i++){
marker = new google.maps.Marker({
position: {
lat: data[i]['py'],
lng: data[i]['px'],
},
map: map,
});
}
}
}
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 14,
center: { lat: -23.54, lng: -46.69 },
});
setMarkers(map);
}
window.initMap = initMap;
</script>
Usually one would use a global variable to store references to each marker added to the map. That global variable can be processed each time you wish to remove the markers from the map by looping through all items and calling setMap( null )
<script>
// global array to store references to the markers.
let markers=[];
function setMarkers(map) {
var ws = new WebSocket('ws://localhost:8000/ws/bus/');
ws.onmessage = function(e){
// remove existing markers before adding new ones...
clearmarkers();
var data = JSON.parse(e.data);
for (let i=0; i<data.length; i++){
marker = new google.maps.Marker({
position: {
lat: data[i]['py'],
lng: data[i]['px'],
},
map: map,
});
// add the new marker to the global
markers.push( marker )
}
}
}
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 14,
center: { lat: -23.54, lng: -46.69 },
});
setMarkers( map );
}
const clearmarkers=()=>{
/*
loop through all the markers in the global variable
and set them to null on the map - ie: remove them.
When all have been removed, re-initialise the global
variable as an empty array.
*/
markers.forEach( mkr=>mkr.setMap( null ) );
markers=[];
}
window.initMap = initMap;
</script>
An alternative to deleting and re-adding would be to simply move them by, once again, iterating through the collection of markers and if they are still valid change the position property