Matthew Woodard Matthew Woodard - 1 year ago 94
Javascript Question

How to alternate map markers with jQuery click event?

I am trying to show specific map markers when clicking an accordion element and hide the other markers if they exist.

I am building my markers with this:

function setMarkers (data) {

var items, markers_data = [];

if (data.length > 0) {
items = data;
j = 0;
for (var i = 0; i < items.length; i++) {
var item = items[i];
lat_long = ('"'+item.martygeocoderlatlng+'"');
lat_long = lat_long.replace(/\(|\)/g,'');
lat_long = lat_long.split(',');

lat = lat_long[0].replace('"','');
lng = lat_long[1].replace('"','');

marker_id =;

if (lat != undefined && lng != undefined) {
var icon = 'community.png';

lat : lat,
lng : lng,
id: marker_id,
title : item.title.rendered,
infoWindow: {
content: '<div class="infoWindow"><h3>'+ item.title.rendered +'</h3>' + item.content.rendered + '<strong>Phone:</strong> <a target="_blank" href="tel:'+item.aoi_phone+'">'+item.aoi_phone+'</a><!--<br><strong>Hours:</strong> '+ item.aoi_hours +'--><br><a href="'+item.aoi_url+'">Visit Website</a></div>'
icon : {
//anchor:new google.maps.Point(scaledSize/4,scaledSize/4),
size:new google.maps.Size(25,25)
// console.log(markers_data);


I am alternating the data passed to the setMarkers function with this:

jQuery('#poi_cat_amusementattractions').one('click', function(e) {
var xhr_cat_amuse = jQuery.getJSON('path/to/json');
jQuery('#poi_cat_dining').one('click', function(e) {
var xhr_cat_dine = jQuery.getJSON('path/to/json');

Which works to bring the markers on the map, but how can I remove any existing markers when clicking the element?

I am also using this plugin for gmaps.

Answer Source

The library you mentioned in the comments have the removeMarkers function (clears all of the markers already added to the map).

You can call this function inside your setMarkers function, right before your call to addMarkers:

function setMarkers (data) {

    // Clear the map from all markers

    // Add new markers to the map