Добавить и удалить несколько маркеров на Google Maps JS
<script defer src="https://maps.googleapis.com/maps/api/js?language=en&key=your_api_key" type="text/javascript"></script>
<script>
$(function(){
var map;
var markersArray = [];
var markersOnMap;
var bounds = new google.maps.LatLngBounds();
var loc;
var InforObj = [];
var mapOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP };
map = new google.maps.Map(document.getElementById("drivers-map"), mapOptions);
window.onload = function() {
renderMapWithDetail();
setInterval(() => {
renderMapWithDetail();
removeMarkers();
}, 10000);
};
function renderMapWithDetail() {
$.get('your_route_to_get_maps_data', function(data) {
markersOnMap = data.markers_on_map;
for (var i = 0; i < markersOnMap.length; i++) {
if (markersOnMap[i].LatLng[0].lat !== null && markersOnMap[i].LatLng[0].lng !== null) {
var contentString = `<div id="content">
<img src="${ markersOnMap[i].img_url} " width="50" >
<h5> ${markersOnMap[i].driverName}</h5>
<p class="company-name-map-window">Company: ${markersOnMap[i].providerName}</p>
<a href="${markersOnMap[i].stream_route}" class="btn btn-dark btn-sm">
<i class="fa fa-video"></i>
</a>
</div>`;
addMarker(markersOnMap[i].LatLng[0], contentString);
}
}
map.fitBounds(bounds);
map.panToBounds(bounds);
});
}
function addMarker(location, contentString) {
console.log(location);
var marker = new google.maps.Marker({
position: location,
map: map,
});
const infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 300
});
marker.addListener('click', function() {
closeOtherInfo();
infowindow.open(marker.get('map'), marker);
InforObj[0] = infowindow;
});
markersArray.push(marker)
loc = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
bounds.extend(loc);
}
function closeOtherInfo() {
if (InforObj.length > 0) {
/* detach the info-window from the marker ... undocumented in the API docs */
InforObj[0].set("marker", null);
/* and close it */
InforObj[0].close();
/* blank the array */
InforObj.length = 0;
}
}
function removeMarkers() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
});
</script>
Terrible Tern