Search code examples
javascripthtmlgoogle-mapslistener

Google Maps API - Is there a way to reverse a listener on the next click?


I have a function which allows me to click on a marker and it provides me with an info box and another marker.

function addMarker(props){
                var marker = new google.maps.Marker({
                    position:props.coords,
                    map: map,
                    icon:props.iconImage
                });

                if(props.content){
                    var infoWindow = new google.maps.InfoWindow({
                      content:props.content
                    });

                    marker.addListener('click', function () {
                        infoWindow.open(map, marker);
                    });
                    marker.addListener('click', function () {
                        addMarker({
                        coords:{lat: 59.896874,lng: -5.125914},
                        iconImage:'pointer12s.png',
                        content:'<h1>destination</h1>'                
                        }); 
                    });
                  
                }

            }

Is there a way to then remove these on the next click?

I have tried putting in variations of:

.removeEventListener

But i am unsure whether to put it into the same function or use a different one?


Solution

  • One option would be to keep a reference to the marker that was added. If it hasn't been added, create the marker, if it already exists, hide it (call setMap(null)) then set it to null. Close the InfoWindow when you remove the marker.

      var addedMarker;
      function addMarker(props) {
        var marker = new google.maps.Marker({
          position: props.coords,
          map: map,
          icon: props.iconImage
        });
    
        if (props.content) {
          var infoWindow = new google.maps.InfoWindow({
            content: props.content
          });
          marker.infowindow = infoWindow;
          marker.addListener('click', function() {
            infoWindow.open(map, marker);
          });
          marker.addListener('click', function() {
            if (!addedMarker || !addedMarker.setMap) {
            addedMarker = addMarker({
              coords: {
                lat: 59.896874,
                lng: -5.125914
              },
              // iconImage: 'pointer12s.png',
              content: '<h1>destination</h1>'
            });
            } else {
              this.infowindow.close();
              addedMarker.setMap(null);
              addedMarker = null;
            }
          });
        }
        return marker;
      }
    
    

    Proof of concept fiddle

    code snippet:

    (function(exports) {
      "use strict";
      var map;
      function initMap() {
        var myLatLng = {
          lat: 59.896874,
          lng: -5.125914
        };
        map = new google.maps.Map(document.getElementById("map"), {
          zoom: 8,
          center: myLatLng
        });
        addMarker({
          coords: {
            lat: 59.8,
            lng: -5.0
          },
          content: "content"
        });
      }
      var addedMarker;
      function addMarker(props) {
        var marker = new google.maps.Marker({
          position: props.coords,
          map: map,
          icon: props.iconImage
        });
    
        if (props.content) {
          var infoWindow = new google.maps.InfoWindow({
            content: props.content
          });
          marker.infowindow = infoWindow;
          marker.addListener('click', function() {
            infoWindow.open(map, marker);
          });
          marker.addListener('click', function() {
            if (!addedMarker || !addedMarker.setMap) {
            addedMarker = addMarker({
              coords: {
                lat: 59.896874,
                lng: -5.125914
              },
              // iconImage: 'pointer12s.png',
              content: '<h1>destination</h1>'
            });
            } else {
              this.infowindow.close();
              addedMarker.setMap(null);
              addedMarker = null;
            }
          });
        }
        return marker;
      }
      exports.initMap = initMap;
    })((this.window = this.window || {}));
    /* Always set the map height explicitly to define the size of the div
           * element that contains the map. */
    
    #map {
      height: 100%;
    }
    
    
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    <!DOCTYPE html>
    <html>
    
    <head>
      <title>Simple Markers</title>
      <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
      <script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap&libraries=&v=weekly" defer></script>
      <!-- jsFiddle will insert css and js -->
    </head>
    
    <body>
      <div id="map"></div>
    </body>
    
    </html>