Matthew Woodard Matthew Woodard - 1 month ago 20
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];
j++
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 = item.id;

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

markers_data.push({
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 : {
url:'/wp-content/plugins/lstar-custom/assets/img/list_marker_'+j+".png",
//anchor:new google.maps.Point(scaledSize/4,scaledSize/4),
size:new google.maps.Size(25,25)
},
animation:google.maps.Animation.DROP,
});
}
}
}
// console.log(markers_data);
map.addMarkers(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');
xhr_cat_amuse.done(setMarkers);
});
jQuery('#poi_cat_dining').one('click', function(e) {
var xhr_cat_dine = jQuery.getJSON('path/to/json');
xhr_cat_dine.done(setMarkers);
});


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.
https://hpneo.github.io/gmaps/

Answer

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
    map.removeMarkers();

    // Add new markers to the map
    map.addMarkers(markers_data);
}