-1

I have made a custom Google map with two sets of markers. I'm trying to write a function to clear the markers but can't get it to work.

The function:

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

This works when the markers are in the lat, long format like below:

var locs1 = [
{lat: 51.2, lng: 0},
{lat: 52, lng: 0.3}
]

But when I use an array to define the markers (as below) it no longer works:

var locs1 = [
['Name', 51.2, 0, 'Info'],
['Name', 52, 0.3, 'Info']
];

How can I make the clearMarkers function work properly?

Full code can be found in this Fiddle to help understand context.

chris45
  • 261
  • 1
  • 4
  • 14
  • Please provide a [mcve] **in the question itself** that demonstrates the problem. Neither of the `locs1` objects you posted are the array of markers, and you haven't posted the code that creates the markers array from them. – geocodezip Jan 18 '17 at 21:32
  • Your fiddle has a javascript error `Uncaught ReferenceError: markers is not defined` – geocodezip Jan 18 '17 at 21:34
  • Sorry fella, I'm still getting used to StackOverflow. Will bear this in mind for future questions. – chris45 Jan 25 '17 at 14:58

2 Answers2

1

Your variable markers should be global and not declared in function.

I edited your fiddle.

var markers = [];

var locs1 = [
['Name', 51.2, 0, 'Info'],
['Name', 52, 0.3, 'Info']
];

var locs2 = [
['Name', 53, -1.93, ' Info'], ['Name', 51, -1.8979, 'Info']
];
Yoleth
  • 1,269
  • 7
  • 15
  • Thank you. Just looked over the updated code in the fiddle and I think I understand, will keep fiddling. – chris45 Jan 25 '17 at 15:01
0

I'v had this problem before. You need to keep a list or array of the Markers, then iterate over them all to clear them. Simply setting a set of cordinates to null won't necessarily clear a marker that was already there, as it is a different object.

Google Map API - Removing Markers

Community
  • 1
  • 1