Search code examples
javascriptgoogle-maps-api-3google-maps-markers

how to remove a single marker from google map


I am trying to add a marker to a Google Map and then to remove it.

<html>

<head>
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
  <meta charset="utf-8">
  <title>MapsApi</title>

  <style>
    #map_canvas {
      width: 100%;
      height: 500px;
      background-color: #CCC;
    }

    #menu_bar {
      width: 100%;
      height: 150px;
      position: absolute;
      bottom: 0px;
      background-color: #CCC;
      border-top: 1px solid red;
    }

    body {
      padding: 0px;
      margin: 0px;
    }
  </style>
  <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
  <script type="text/javascript">
    var map;
    var markers = [];

    function initialize() {
      var myLatlng = new google.maps.LatLng(44.5403, -78.5463);
      var mapOptions = {
        zoom: 4,
        center: myLatlng
      }
      var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

      google.maps.event.addListener(map, 'click', function(event) {
        addMarker(event.latLng);
      });


      // add marker to positon
      function addMarker(location) {
        var marker = new google.maps.Marker({
          position: location,
          map: map
        });
        google.maps.event.addListener(marker, 'click', function(event) {
          this.setMap(null);
        });

        markers.push(marker);
      }

      // Sets the map on all markers in the array.
      function setAllMap(map) {
        for (var i = 0; i < markers.length; i++) {
          markers[i].setMap(map);
        }
      }
    }

    google.maps.event.addDomListener(window, 'load', initialize);
  </script>

</head>

<body>
  <div id="map_canvas"></div>
  <div id="menu_bar"></div>
</body>

</html>

Here is the problem: how should I set the value of markers.push(marker) because as I have removed one marker, its value must be less than the expected stored value.


Solution

  • The easier answer is that you don't remove the marker from the markers array. All you do is identify the marker you want to remove from the map and then use setMap(null).

    markers[indexOfMarker].setMap(null);
    

    This way you can use the following if you want to add the marker back at some point:

    markers[indexOfMarker].setMap(map);