Didin Wahyu
Didin Wahyu

Reputation: 21

how to remove single marker google maps api v3

i try to remove google maps marker with clearoverlays(), but i cant resolve that problem.. all the thing that i want is to remove single marker from my map. but i can only remove all marker. i have use array for my code.. here is my code

   <!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>

<script>
var map;
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
var markers = [];

function initialize()
{
var mapProp = {
  center:myCenter,
  zoom:5,
  mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("googleMap"),mapProp);

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

  google.maps.event.addListener(map, 'rightclick', function(){
    clearOverlays();
  });

}

function placeMarker(e) {

  var marker = new google.maps.Marker({
    position: e,
    map: map,
  });
  var infowindow = new google.maps.InfoWindow({
    content: 'Latitude: ' + e.lat() + '<br>Longitude: ' + e.lng()
  });
  infowindow.open(map,marker);
  markers.push(marker);
}

function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}

// Removes the overlays from the map, but keeps them in the array.
function clearOverlays() {
  for (var i = markers.length; i > 0; i--){
        markers[markers.length-i].setMap(null);
  }
}

// Shows any overlays currently in the array.
function showOverlays() {
  setAllMap(map);
}

// Deletes all markers in the array by removing references to them.
function deleteOverlays() {
  clearOverlays();
  markers = [];
}


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

<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
<input onclick="clearOverlays();" type=button value="Hide Overlays">
      <input onclick="showOverlays();" type=button value="Show All Overlays">
      <input onclick="deleteOverlays();" type=button value="Delete Overlays">
      <input onclick="deleteMarker(marker);" type=button value="delete mark">
</body>
</html>

Upvotes: 2

Views: 4264

Answers (1)

Amit Arya
Amit Arya

Reputation: 142

Ok here's the simple trick to remove single marker from google map.

var icon = "icon.png";

                var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
                title: 'I am from Nepal.',
                icon: icon,
                });

If you're a photoshop geek, set your icon size to 1px , reduce opacity to make it transparent.. It will work like a charm.. have a nice time..

Upvotes: 1

Related Questions