My code takes two inputs, address and distance then iterates thru an array containing locations and puts a marker on the map if the location in within the distance. When i'm starting a new search i want to remove all the previous markers from the map. My code only removes one marker which is the address provided by the user, what am I missing?
//Array of all map markers
var markers = [];
// Loading Map
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 54.188, lng: -2.878},
zoom: 6
});
//Creating a Geocoder object
var geocoder = new google.maps.Geocoder();
//Calling a
document.getElementById('submit').addEventListener('click', function() {
geocodeAddress(geocoder, map);
});
//Geocoding function
function geocodeAddress(geocoder, resultsMap) {
//Removing all markers form the map each time this function is called
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers = [];
}
var address = document.getElementById('address').value;
var distance = document.getElementById('distance').value;
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var userMarker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
icon: 'img/bluedot.png'
});
markers.push(userMarker);
//Creating track markers
for (var i = 0; i < mxTracks.length; i++) {
var trackMarker = new google.maps.Marker({
position: new google.maps.LatLng(mxTracks[i][2], mxTracks[i][3])
});
markers.push(trackMarker);
//If markers are within a set distance add them to a map
if (google.maps.geometry.spherical.computeDistanceBetween(userMarker.getPosition(), trackMarker.getPosition()) < parseInt(distance) * 1609.34) {
trackMarker.setMap(resultsMap);
}
}
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}