Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove a single marker from google map

I am working on google maps i am trying to add markers to a google map and then tried to remove it but now as i have done both adding and removing with the code below

    <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>

but here is a problem now how should i set the value of markers.push(marker) because as i have removed one marker so its value must be less than its expected stored.. can any one help

like image 452
Johnfranklien Avatar asked Nov 20 '13 16:11

Johnfranklien


1 Answers

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);
like image 85
Andy Avatar answered Nov 14 '22 15:11

Andy