Search code examples
vue.jsmarkers

How to remove particular marker form google map when user start retype another place name in textbox


I'm trying to remove place marker form map. when user perform keypress event in input field.in my project i have two gmap-autocomplete components the both creat diffrent markers on map.so when i use setMap(null) then it remove all the markes form map.i need to remove one at a time.Please help Thank you.!

 refreshMapEndSource(event) {
      if (document.getElementById('txtDestination').value != '') {
        let endOrigin = document.getElementById('txtDestination').value
        if (this.markRemEnd != null) {
          if (endOrigin != this.markRemEnd.fplace) {
            console.log('NOt Equal')
             console.log(this.$google.marker[i].fplace)
              this.$google.marker[0].setMap(null)
          }
        }
      } else {
        //
      }
    }

Solution

  • I'm not sure what are you trying to do but I guess you want to remove markers which created from either A or B component.

    To do this when you create marker you have to keep it in some array let's call it as markers:

    let markers = []
    
    let marker = new google.maps.Marker({
      position: location,
      map: map
    })
    
    markers.push({
      type: 'A' // or 'B',
      marker
    })
    

    Then whenever you want to remove markers from A:

    markers.forEach(marker => {
      if (marker.type === 'A') marker.marker.setMap(null)
    })
    
    markers = this.markers.filter(marker => marker.type !== 'A')
    

    Well if my guess is wrong and you really want to remove particular marker which is pretty similar you have to know which marker you have remove.

    markers.push({
      name: 'abc',
      marker
    })
    
    markers.forEach(marker => {
      if (marker.name === 'abc') marker.marker.setMap(null)
    })