I'm creating an application which gets the real-time location and renders to Google Map. After a specific time interval, I have to remove old markers and need to render the udpated markers.
Below is my code
function initMap(rtl_data) {
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer();
var latlng = new google.maps.LatLng(24.238162, 45.156379);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var marker = []
var map = new google.maps.Map(document.getElementById("map"),myOptions);
directionsDisplay.setMap(map);
makeMarkers(rtl_data)
function makeMarkers(rtl_data){
// Drivers Location Markers
deleteMarkers()
features = []
marker = []
drivers_latlng = rtl_data.drivers_latest_location
drivers_latlng.forEach(function(e){
features.push({
position: new google.maps.LatLng(e.lat, e.lng),
type: e.order_id,
title: e.driver_id,
description: e.order_id ? "Ongoing order: "+e.order_id : "No order assigned."
})
})
image = "/files/truck.png"
infoWindow = new google.maps.InfoWindow();
for (i = 0; i < features.length; i++) {
marker = new google.maps.Marker({
position: features[i].position,
map: map,
title: features[i].title,
type: features[i].type,
icon: image,
description: features[i].description
});
//Attach click event to the marker.
(function (marker) {
google.maps.event.addListener(marker, "click", function (e) {
//Wrap the content inside an HTML DIV in order to set height and width of InfoWindow.
infoWindow.setContent("<div style = 'width:200px;min-height:40px'>" + marker.description + "</div>");
infoWindow.open(map, marker);
});
})(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < marker.length; i++) {
marker[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setMapOnAll(null);
console.log('clearMarkers')
}
// Shows any markers currently in the array.
function showMarkers() {
setMapOnAll(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
console.log('deleteMarkers')
clearMarkers();
marker = [];
}
}
// Fetch Realtime using time interval
setInterval(function() {
frappe.call({ // Simple AJAX Call which returns locations and location realated data.
method: "get_drivers_locations",
async: false,
callback: function(r){
rtl_data = r.message
}
})
makeMarkers(rtl_data)
}, 5000);
I already used Method's which is used in the documentaion by Google Map. Using ClearMarkers the old markers get cleared. But in my case it is not working. When I run above code it displaying me both old and upadted markers.
See below screenshot which is repetating markers with updated locations.