-1

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);
    }
  });
}
  • duplicate of [Google Maps API v3: How to remove all markers?](http://stackoverflow.com/questions/1544739/google-maps-api-v3-how-to-remove-all-markers) – geocodezip Jan 08 '17 at 21:53

1 Answers1

0

You have a typo in your code:

//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 = [];
}

removes the first marker then sets the markers array to []; you want to process the whole array, then set it to [].

//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 = [];

proof of concept fiddle

code snippet:

google.maps.event.addDomListener(window, "load", initMap);
//Array of all map markers
var markers = [];
var mxTracks = [
  ["Brighton, UK", 0, 50.82253000000001, -0.13716299999998682],
  ["Cambridge, UK", 1, 52.205337, 0.12181699999996454]
];
// 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);
      }
    });
  }
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<input id="address" value="London, UK" />
<input id="submit" type="button" value="submit" />
<input id="distance" value="100" />
<div id="map"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245