I have been working on a program that dynamically loads JSON data onto a map as markers when the user pans and zooms. However, I am facing an issue where I need to clear the existing markers each time the user interacts with the map in order to load new ones. The current code snippet successfully removes the markers but only when it is attached to a button click event listener.
var features = map.data.addGeoJson(data);
google.maps.event.addDomListener(document.getElementById('removeBtn'), 'click', function () {
for (var i = 0; i < features.length; i++)
map.data.remove(features[i]);
});
Here is the code snippet:
function initialize() {
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
center: new google.maps.LatLng(39.50, -98.35),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions)
google.maps.event.addListener(map, 'idle', function() {
try{
for (var i = 0; i < features.length; i++) {
map.data.remove(features[i]);
}
}catch(err){
console.log("fail")
}
$.getJSON("/static/json/data.json", function(data) {
var features = map.data.addGeoJson(data) {
});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
The GEOJSON data:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [
-84.375,
36.31512514748051
]
}
}
]
}
I'm seeking guidance on how to ensure that the 'idle' event listener clears existing markers before loading new ones. How can I approach this?