Google Maps API V3: How to Remove All Markers

Google Map API - Removing Markers

You need to keep an array of the google.maps.Marker objects to hide (or remove or run other operations on them).

In the global scope:

var gmarkers = [];

Then push the markers on that array as you create them:

var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude),
title: locations[i].title,
icon: icon,
map:map
});

// Push your newly created marker into the array:
gmarkers.push(marker);

Then to remove them:

function removeMarkers(){
for(i=0; i<gmarkers.length; i++){
gmarkers[i].setMap(null);
}
}

working example (toggles the markers)

code snippet:

var gmarkers = [];var RoseHulman = new google.maps.LatLng(39.483558, -87.324593);var styles = [{  stylers: [{    hue: "black"  }, {    saturation: -90  }]}, {  featureType: "road",  elementType: "geometry",  stylers: [{    lightness: 100  }, {    visibility: "simplified"  }]}, {  featureType: "road",  elementType: "labels",  stylers: [{    visibility: "on"  }]}];
var styledMap = new google.maps.StyledMapType(styles, { name: "Campus"});var mapOptions = { center: RoseHulman, zoom: 15, mapTypeControl: true, zoomControl: true, zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL }, mapTypeControlOptions: { mapTypeIds: ['map_style', google.maps.MapTypeId.HYBRID], style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }, scrollwheel: false, streetViewControl: true,
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);map.mapTypes.set('map_style', styledMap);map.setMapTypeId('map_style');
var infowindow = new google.maps.InfoWindow({ maxWidth: 300, infoBoxClearance: new google.maps.Size(1, 1), disableAutoPan: false});
var marker, i, icon, image;
var locations = [{ "id": "1", "category": "6", "campus_location": "F2", "title": "Alpha Tau Omega Fraternity", "description": "<p>Alpha Tau Omega house</p>", "longitude": "-87.321133", "latitude": "39.484092"}, { "id": "2", "category": "6", "campus_location": "B2", "title": "Apartment Commons", "description": "<p>The commons area of the apartment-style residential complex</p>", "longitude": "-87.329282", "latitude": "39.483599"}, { "id": "3", "category": "6", "campus_location": "B2", "title": "Apartment East", "description": "<p>Apartment East</p>", "longitude": "-87.328809", "latitude": "39.483748"}, { "id": "4", "category": "6", "campus_location": "B2", "title": "Apartment West", "description": "<p>Apartment West</p>", "longitude": "-87.329732", "latitude": "39.483429"}, { "id": "5", "category": "6", "campus_location": "C2", "title": "Baur-Sames-Bogart (BSB) Hall", "description": "<p>Baur-Sames-Bogart Hall</p>", "longitude": "-87.325714", "latitude": "39.482382"}, { "id": "6", "category": "6", "campus_location": "D3", "title": "Blumberg Hall", "description": "<p>Blumberg Hall</p>", "longitude": "-87.328321", "latitude": "39.483388"}, { "id": "7", "category": "1", "campus_location": "E1", "title": "The Branam Innovation Center", "description": "<p>The Branam Innovation Center</p>", "longitude": "-87.322614", "latitude": "39.48494"}, { "id": "8", "category": "6", "campus_location": "G3", "title": "Chi Omega Sorority", "description": "<p>Chi Omega house</p>", "longitude": "-87.319905", "latitude": "39.482071"}, { "id": "9", "category": "3", "campus_location": "D1", "title": "Cook Stadium/Phil Brown Field", "description": "<p>Cook Stadium at Phil Brown Field</p>", "longitude": "-87.325258", "latitude": "39.485007"}, { "id": "10", "category": "1", "campus_location": "D2", "title": "Crapo Hall", "description": "<p>Crapo Hall</p>", "longitude": "-87.324368", "latitude": "39.483709"}, { "id": "11", "category": "6", "campus_location": "G3", "title": "Delta Delta Delta Sorority", "description": "<p>Delta Delta Delta</p>", "longitude": "-87.317477", "latitude": "39.482951"}, { "id": "12", "category": "6", "campus_location": "D2", "title": "Deming Hall", "description": "<p>Deming Hall</p>", "longitude": "-87.325822", "latitude": "39.483421"}, { "id": "13", "category": "5", "campus_location": "F1", "title": "Facilities Operations", "description": "<p>Facilities Operations</p>", "longitude": "-87.321782", "latitude": "39.484916"}, { "id": "14", "category": "2", "campus_location": "E3", "title": "Flame of the Millennium", "description": "<p>Flame of Millennium sculpture</p>", "longitude": "-87.323306", "latitude": "39.481978"}, { "id": "15", "category": "5", "campus_location": "E2", "title": "Hadley Hall", "description": "<p>Hadley Hall</p>", "longitude": "-87.324046", "latitude": "39.482887"}, { "id": "16", "category": "2", "campus_location": "F2", "title": "Hatfield Hall", "description": "<p>Hatfield Hall</p>", "longitude": "-87.322340", "latitude": "39.482146"}, { "id": "17", "category": "6", "campus_location": "C2", "title": "Hulman Memorial Union", "description": "<p>Hulman Memorial Union</p>", "longitude": "-87.32698", "latitude": "39.483574"}, { "id": "18", "category": "1", "campus_location": "E2", "title": "John T. Myers Center for Technological Research with Industry", "description": "<p>John T. Myers Center for Technological Research With Industry</p>", "longitude": "-87.322984", "latitude": "39.484063"}, { "id": "19", "category": "6", "campus_location": "A2", "title": "Lakeside Hall", "description": "<p></p>", "longitude": "-87.330612", "latitude": "39.482804"}, { "id": "20", "category": "6", "campus_location": "F2", "title": "Lambda Chi Alpha Fraternity", "description": "<p>Lambda Chi Alpha</p>", "longitude": "-87.320999", "latitude": "39.48305"}, { "id": "21", "category": "1", "campus_location": "D2", "title": "Logan Library", "description": "<p>Logan Library</p>", "longitude": "-87.324851", "latitude": "39.483408"}, { "id": "22", "category": "6", "campus_location": "C2", "title": "Mees Hall", "description": "<p>Mees Hall</p>", "longitude": "-87.32778", "latitude": "39.483533"}, { "id": "23", "category": "1", "campus_location": "E2", "title": "Moench Hall", "description": "<p>Moench Hall</p>", "longitude": "-87.323695", "latitude": "39.483471"}, { "id": "24", "category": "1", "campus_location": "G4", "title": "Oakley Observatory", "description": "<p>Oakley Observatory</p>", "longitude": "-87.31616", "latitude": "39.483789"}, { "id": "25", "category": "1", "campus_location": "D2", "title": "Olin Hall and Olin Advanced Learning Center", "description": "<p>Olin Hall</p>", "longitude": "-87.324550", "latitude": "39.482796"}, { "id": "26", "category": "6", "campus_location": "C3", "title": "Percopo Hall", "description": "<p>Percopo Hall</p>", "longitude": "-87.328182", "latitude": "39.482121"}, { "id": "27", "category": "6", "campus_location": "G3", "title": "Public Safety Office", "description": "<p>The Office of Public Safety</p>", "longitude": "-87.320377", "latitude": "39.48191"}, { "id": "28", "category": "1", "campus_location": "E2", "title": "Rotz Mechanical Engineering Lab", "description": "<p>Rotz Lab</p>", "longitude": "-87.323247", "latitude": "39.483711"}, { "id": "28", "category": "6", "campus_location": "C2", "title": "Scharpenberg Hall", "description": "<p>Scharpenberg Hall</p>", "longitude": "-87.328139", "latitude": "39.483582"}, { "id": "29", "category": "6", "campus_location": "G2", "title": "Sigma Nu Fraternity", "description": "<p>The Sigma Nu house</p>", "longitude": "-87.31999", "latitude": "39.48374"}, { "id": "30", "category": "6", "campus_location": "E4", "title": "South Campus / Rose-Hulman Ventures", "description": "<p></p>", "longitude": "-87.330623", "latitude": "39.417646"}, { "id": "31", "category": "6", "campus_location": "C3", "title": "Speed Hall", "description": "<p>Speed Hall</p>", "longitude": "-87.326632", "latitude": "39.482121"}, { "id": "32", "category": "3", "campus_location": "C1", "title": "Sports and Recreation Center", "description": "<p></p>", "longitude": "-87.3272", "latitude": "39.484874"}, { "id": "33", "category": "6", "campus_location": "F2", "title": "Triangle Fraternity", "description": "<p>Triangle fraternity</p>", "longitude": "-87.32113", "latitude": "39.483659"}, { "id": "34", "category": "6", "campus_location": "B3", "title": "White Chapel", "description": "<p>The White Chapel</p>", "longitude": "-87.329367", "latitude": "39.482481"}, { "id": "35", "category": "6", "campus_location": "F2", "title": "Women's Fraternity Housing", "description": "", "image": "", "longitude": "-87.320753", "latitude": "39.482401"}, { "id": "36", "category": "3", "campus_location": "E1", "title": "Intramural Fields", "description": "<p></p>", "longitude": "-87.321267", "latitude": "39.485934"}, { "id": "37", "category": "3", "campus_location": "A3", "title": "James Rendel Soccer Field", "description": "<p></p>", "longitude": "-87.332135", "latitude": "39.480933"}, { "id": "38", "category": "3", "campus_location": "B2", "title": "Art Nehf Field", "description": "<p>Art Nehf Field</p>", "longitude": "-87.330923", "latitude": "39.48022"}, { "id": "39", "category": "3", "campus_location": "B2", "title": "Women's Softball Field", "description": "<p></p>", "longitude": "-87.329904", "latitude": "39.480278"}, { "id": "40", "category": "3", "campus_location": "D1", "title": "Joy Hulbert Tennis Courts", "description": "<p>The Joy Hulbert Outdoor Tennis Courts</p>", "longitude": "-87.323767", "latitude": "39.485595"}, { "id": "41", "category": "6", "campus_location": "B2", "title": "Speed Lake", "description": "", "image": "", "longitude": "-87.328134", "latitude": "39.482779"}, { "id": "42", "category": "5", "campus_location": "F1", "title": "Recycling Center", "description": "", "image": "", "longitude": "-87.320098", "latitude": "39.484593"}, { "id": "43", "category": "1", "campus_location": "F3", "title": "Army ROTC", "description": "", "image": "", "longitude": "-87.321342", "latitude": "39.481992"}, { "id": "44", "category": "2", "campus_location": " ", "title": "Self Made Man", "description": "", "image": "", "longitude": "-87.326272", "latitude": "39.484481"}, { "id": "P1", "category": "4", "title": "Percopo Parking", "description": "", "image": "", "longitude": "-87.328756", "latitude": "39.481587"}, { "id": "P2", "category": "4", "title": "Speed Parking", "description": "", "image": "", "longitude": "-87.327361", "latitude": "39.481694"}, { "id": "P3", "category": "4", "title": "Main Parking", "description": "", "image": "", "longitude": "-87.326245", "latitude": "39.481446"}, { "id": "P4", "category": "4", "title": "Lakeside Parking", "description": "", "image": "", "longitude": "-87.330848", "latitude": "39.483284"}, { "id": "P5", "category": "4", "title": "Hatfield Hall Parking", "description": "", "image": "", "longitude": "-87.321417", "latitude": "39.482398"}, { "id": "P6", "category": "4", "title": "Women's Fraternity Parking", "description": "", "image": "", "longitude": "-87.320977", "latitude": "39.482315"}, { "id": "P7", "category": "4", "title": "Myers and Facilities Parking", "description": "", "image": "", "longitude": "-87.322243", "latitude": "39.48417"}, { "id": "P8", "category": "4", "title": "", "description": "", "image": "", "longitude": "-87.323241", "latitude": "39.484758"}, { "id": "P9", "category": "4", "title": "", "description": "", "image": "", "longitude": "-87.323617", "latitude": "39.484311"}, { "id": "P10", "category": "4", "title": "", "description": "", "image": "", "longitude": "-87.325714", "latitude": "39.484584"}, { "id": "P11", "category": "4", "title": "", "description": "", "image": "", "longitude": "-87.32778", "latitude": "39.484145"}, { "id": "P12", "category": "4", "title": "", "description": "", "image": "", "longitude": "-87.329035", "latitude": "39.4848"}];
for (i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i].latitude, locations[i].longitude), title: locations[i].title, map: map }); gmarkers.push(marker); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { if (locations[i].description !== "" || locations[i].title !== "") { infowindow.setContent('<div class="content" id="content-' + locations[i].id + '" style="max-height:300px; font-size:12px;"><h3>' + locations[i].title + '</h3>' + '<hr class="grey" />' + hasImage(locations[i]) + locations[i].description) + '</div>'; infowindow.open(map, marker); } } })(marker, i));}
function toggleMarkers() { for (i = 0; i < gmarkers.length; i++) { if (gmarkers[i].getMap() != null) gmarkers[i].setMap(null); else gmarkers[i].setMap(map); }}
function hasImage(location) { return '';}
html,body,#map {  height: 100%;  width: 100%;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script><div id="controls">  <input type="button" value="Toggle All Markers" onClick="toggleMarkers()" /></div><div id="map"></div>

Google maps delete all markers and then create new

You need to change:

      // Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
marker.setMap(null);
markers = [];

to

  // Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});

and make google.maps.event.addListener(map, 'click', function(event) {

google.maps.event.addListener(map, 'click', function(event) {
geocoder.geocode({
'latLng': event.latLng
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
markers.forEach(function(marker) {
marker.setMap(null);
})
document.getElementById('pac-input').value = results[0].formatted_address;
}
}
});
placeMarker(event.latLng);
});

EDIT:

Replace:

    // Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
}));

with:

placeMarker(place.geometry.location)

JSFiddle:

function initAutocomplete() {  var myOptions = {    zoom: 5,    mapTypeId: google.maps.MapTypeId.ROADMAP,    mapTypeControl: false  }
var map; var marker; var geocoder = new google.maps.Geocoder(); var address = document.getElementById('pac-input').value; var infowindow = new google.maps.InfoWindow(); var markers = [];
geocoder.geocode({ address: address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK && results.length) { if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
//create map map = new google.maps.Map(document.getElementById("map"), myOptions);
//center map map.setCenter(results[0].geometry.location);
//create marker marker = new google.maps.Marker({ position: results[0].geometry.location, map: map, title: document.getElementById('pac-input').value, });
// Create the search box and link it to the UI element. var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.SearchBox(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current maps viewport. map.addListener('bounds_changed', function() { searchBox.setBounds(map.getBounds()); });
// Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener('places_changed', function() { var places = searchBox.getPlaces();
if (places.length == 0) { return; }
// Clear out the old markers. markers.forEach(function(marker) { marker.setMap(null); });
// For each place, get the icon, name and location. var bounds = new google.maps.LatLngBounds(); places.forEach(function(place) { var icon = { url: place.icon, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(25, 25) }; placeMarker(place.geometry.location) if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); });
google.maps.event.addListener(map, 'click', function(event) { geocoder.geocode({ 'latLng': event.latLng }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[0]) { markers.forEach(function(marker) { marker.setMap(null); }); document.getElementById('pac-input').value = results[0].formatted_address; placeMarker(event.latLng); } } }); });
function placeMarker(location) { if (marker) { marker.setPosition(location); } else { marker = new google.maps.Marker({ position: place.geometry.location, map: map, title: place.name, }); } } } } else { $('#map').css({ 'height': '15px' }); $('#map').html("Oops! address could not be found, please make sure the address is correct."); resizeIframe(); } });
function resizeIframe() { var me = window.name; if (me) { var iframes = parent.document.getElementsByName(me); if (iframes && iframes.length == 1) { height = document.body.offsetHeight; iframes[0].style.height = height + "px"; } } }}
/* 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;}
<input id="pac-input" class="controls" type="text" placeholder="Search Box"><div id="map"></div><!-- Replace the value of the key parameter with your own API key. --><script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBZbI5EJHVyNPd07tdhGgIODBpuqCePlIw&libraries=places&callback=initAutocomplete">

</script>

Remove all markers google map v3

else {
alert("false");
showmarkers = true;
for(var lp=0;lp<markers.length;lp++){
markers[lp].setMap(null);
}
}

Unable to remove all markers in Google Map v3

var marker = new MarkerWithLabel({
map: map,
position: new google.maps.LatLng(markers[i].lat,markers[i].lng),
icon: pinImage,
shadow: pinShadow,
labelContent: markers[i].count,
labelAnchor: new google.maps.Point(12, -5),
labelClass: "labels"
});
markersToRemove.push(marker); // markersToRemove is a global array

function removeMarkers() {
for(var i = 0; i < markersToRemove.length; i++) {
markersToRemove[i].setMap(null);
}
}

How to clear existing markers in google maps?

Add markers as a property of the googleMaps object, add all markers to it and then adjust the clearAirports function a bit:

googleMaps: {
map: null,
markers: [], //HERE
init: function () {
var self = this;
var $google_maps_item = $('#gmaps');
if ( $google_maps_item.length ) {

var mapOptions = {
zoom: 5,
center: new google.maps.LatLng( 39.615794, 2.998049 ),
scrollwheel: false,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
rotateControl: false,
disableDefaultUI: true
};
self.map = new google.maps.Map(document.getElementById("gmaps"), mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng($google_maps_item.data('lat'), $google_maps_item.data('long')),
map: self.map,
icon: {
path: "M27.648 -41.399q0 -3.816 -2.7 -6.516t-6.516 -2.7 -6.516 2.7 -2.7 6.516 2.7 6.516 6.516 2.7 6.516 -2.7 2.7 -6.516zm9.216 0q0 3.924 -1.188 6.444l-13.104 27.864q-0.576 1.188 -1.71 1.872t-2.43 0.684 -2.43 -0.684 -1.674 -1.872l-13.14 -27.864q-1.188 -2.52 -1.188 -6.444 0 -7.632 5.4 -13.032t13.032 -5.4 13.032 5.4 5.4 13.032z",
scale: 0.6,
strokeWeight: 0.2,
strokeColor: 'black',
strokeOpacity: 1,
fillColor: '#003547',
fillOpacity: 0.85,
}
});
self.markers.push(marker); //HERE: remove if you don't want to add the first marker to the array
self.drawAirports();

}
},
drawAirports: function () {
var self = this;



var $airports = $('.airport_list ul li:visible');
var airports = [];

console.log( 'hemos detectado ' + $airports.length + ' visibles' );

$airports.each( function () {
var airport = {
'airport' : $(this).data('titulo'),
'lat' : $(this).data('lat'),
'long' : $(this).data('long'),
'href' : $(this).data('href')
}
airports[airports.length] = airport;
});


var infobox = null;
for (var i = 0; i < airports.length; i++) {
(function (airport) {
console.log ( base_url + 'img/gmaps/marker.png' );
var marker = new google.maps.Marker({
position: new google.maps.LatLng(airport.lat, airport.long),
map: self.map,
title: airport.airport,
icon: base_url + 'img/gmaps/marker.png',
visible: true
});

google.maps.event.addListener(marker, 'click', function () {
if(infobox) {
infobox.close();
}
infobox = new InfoBox({
content: '<h3>' + airport.airport + '</h3><a class="info" href=""><span>Información</span></a><a class="bags" href=""><span>Equipajes</span></a>',
disableAutoPan: false,
maxWidth: 150,
pixelOffset: new google.maps.Size(-212, -150),
zIndex: null,
boxStyle: {
width: "280px"
},
closeBoxMargin: "0",
closeBoxURL: base_url + "img/gmaps/close.png",
infoBoxClearance: new google.maps.Size(1, 1)
});
infobox.open(map, this);
map.panTo(marker.position);
});

self.markers.push(marker); //HERE
})(airports[i]);
}
},
clearAirports: function () { //We don't need to define google.maps.Map.prototype.clearMarkers, just clear them right here
console.log( this.markers.length + ' Markers to clear' );
for(var i=0; i < this.markers.length; i++){
this.markers[i].setMap(null);
}
this.markers = new Array();
}
}

Google Maps V3 - Remove all Markers

I modified your code. I am keeping the reference of all markers in an array. and inside hideMarkers i am setting their map as null to remove them from map.

 function initialize() {
var mapOptions = {
zoom : 15,
center : new google.maps.LatLng(52.429236, 6.281255),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

var markers = setMarkers(map, access_points);

google.maps.event.addListener(map, 'zoom_changed', function() {
if (map.getZoom() > 15) {
setMarkers(map, access_points);
}
else {
hideMarkers(map, access_points, markers);

}
});

}

var access_points = [ [ 'Location 1', 52.420891, 6.280204 ], [ 'Location 2', 52.420125, 6.279131 ], [ 'Location 3', 52.420125, 6.240125 ] ];

function setMarkers(map, locations) {
var markers= [];
var image = new google.maps.MarkerImage('../images/map/beachflag.png', new google.maps.Size(20, 32), new google.maps.Point(0, 0), new google.maps.Point(0,
32));
var shadow = new google.maps.MarkerImage('../images/map/beachflag_shadow.png', new google.maps.Size(37, 32), new google.maps.Point(0, 0),
new google.maps.Point(0, 32));
var shape = {
coord : [ 1, 1, 1, 20, 18, 20, 18, 1 ],
type : 'poly'
};

for ( var i = 0; i < locations.length; i++) {
var access_point = locations[i];
var myLatLng = new google.maps.LatLng(access_point[1], access_point[2]);
var marker = new google.maps.Marker({
position : myLatLng,
map : map,
shadow : shadow,
icon : image,
shape : shape,
title : access_point[0],
zIndex : access_point[3]
});
markers.push(marker);
}
return markers;
}

function hideMarkers(map, locations, markers) {
/* Remove All Markers */
while(markers.length){
markers.pop().setMap(null);
}

console.log("Remove All Markers");
}


Related Topics



Leave a reply



Submit