0

Each time my code invokes the function search() I would like the google map markers that were placed on the map from the previous search call cleared off the map and the NEW markers placed on the map. I need help clearing out the markers.

function search() {
//loading the map with markers
$('.map').addClass('.map-with-searching');
$.ajax({
  url: 'https://' + getApiURL(),
  data: data,
  contentType: 'application/json',
  type: 'POST',
  success: function (result) {
    $('#universitiesList').html('');
    for (const row of result.payload) {
      locations.push({ lat: row.location.latitude, lng: 
row.location.longitude, university: row.campusName, id:row.campusID});
    }
    //marker.setVisible(false);

    for (i = 0; i < locations.length; i++) {
      marker = new google.maps.Marker({
        position: { lat: locations[i].lat, lng: locations[i].lng },
        map: map,
        data: {
          university: locations[i].university,
          id: locations[i].id,
          name: locations[i].name,
          address: locations[i].address,
          image: locations[i].image,
        }
      });

      map.setCenter(new google.maps.LatLng(locations[i].lat, locations[i].lng));

      marker.addListener('click', function () {
        if (!this.infoWindow) {
          this.infoWindow = new google.maps.InfoWindow({
            content: '<div class="flex marker-pop-up"><div class="image-container"><img id="building" src="' 
            + this.data.image  + '"onerror="imgError(this)"; alt="Smiley face" height="110" width="120" /></div></div></div></div>'
          });
        }
        this.infoWindow.open(map, this);
      })
    };
  },
  error: function (jqXhr, textStatus, errorThrown) {
    //console.log(errorThrown);
  }
})
}
  • Possible duplicate of [Google Maps API v3: How to remove all markers?](https://stackoverflow.com/questions/1544739/google-maps-api-v3-how-to-remove-all-markers) – grooveplex May 21 '19 at 15:37
  • Store references to the markers and when you want to clear them, call .setMap( null ) on each of them – JasonB May 21 '19 at 15:38
  • @JasonB it would be greatly appreciated if you are able to show the code for the solution you are suggesting. thank you. – user11351969 May 21 '19 at 15:40
  • I added an answer that includes it in your code. One odd thing in your example, are you really trying to center the map on every location that came back within the loop? Only the last one will matter. – JasonB May 21 '19 at 18:04

1 Answers1

0

Here's an untested example - store references to the markers and then call .setMap(null) to remove them from the map.

// an array of the markers on the map
let markers = [];

function search() {

  // clear the markers
  for( const marker of markers ) {
    marker.setMap(null);
  }
  markers = [];

  //loading the map with markers
  $('.map').addClass('.map-with-searching');
  $.ajax({
    url: 'https://' + getApiURL(),
    data: data,
    contentType: 'application/json',
    type: 'POST',
    success: function (result) {
      $('#universitiesList').html('');
      for (const row of result.payload) {
        locations.push({ lat: row.location.latitude, lng: row.location.longitude, university: row.campusName, id:row.campusID});
      }
      //marker.setVisible(false);

      for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
          position: { lat: locations[i].lat, lng: locations[i].lng },
          map: map,
          data: {
            university: locations[i].university,
            id: locations[i].id,
            name: locations[i].name,
            address: locations[i].address,
            image: locations[i].image,
          }
        });

        // Store a reference so you can remove markers later
        markers.push( marker );

        map.setCenter(new google.maps.LatLng(locations[i].lat, locations[i].lng));

        marker.addListener('click', function () {
          if (!this.infoWindow) {
            this.infoWindow = new google.maps.InfoWindow({
              content: '<div class="flex marker-pop-up"><div class="image-container"><img id="building" src="' + this.data.image  + '"onerror="imgError(this)"; alt="Smiley face" height="110" width="120" /></div></div></div></div>'
            });
          }
          this.infoWindow.open(map, this);
        });
      };
    },
    error: function (jqXhr, textStatus, errorThrown) {
      //console.log(errorThrown);
    }
  });
}
JasonB
  • 5,747
  • 2
  • 13
  • 25
  • Getting error, Uncaught TypeError: marker.setMap is not a function. – user11351969 May 21 '19 at 18:29
  • Are you really trying to center the map on every location that came back? I want that the focus of the map should be on the placing of the markers. Wether its one marker or multiple markers. Does my code not make sense for such a case? – user11351969 May 21 '19 at 18:30
  • `for( const marker of markers ) {` instead of `in` should fix the error. I also added a line to clear the stored marker array after setting their maps to null, `markers = [];` – JasonB May 21 '19 at 19:02
  • Regarding the map centering, if it is working for you then I wouldn't worry about it. Your JS is recentering the map inside every iteration of the loop which means that the map is centered on the last marker of each set of search results. There is a way to center on a bounding box that wraps around your markers, but that's for another question if you need to do that. – JasonB May 21 '19 at 19:06