1

I based this function on the Google Maps API tutorials.

  • The remove markers part is not working.
  • The infowindow opens only on one marker, even if I click on a different one.

"gpsarray" contains arrays with location information separated by commas.

var map;
var markers = [];

function markersAdd(gpsarray){
    // Remove all Google Maps Markers
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(map);
    }
    markers = [];

    // Loop the array and add the corresponding markers
    for (var i = 0; i < gpsarray.length; i++) {
        gps = gpsarray[i].split(",");
        latitude = parseFloat(gps[4]);
        longitude = parseFloat(gps[3]);
        var marker = new google.maps.Marker({
            position: {lat: latitude, lng: longitude},
            map: map,
            title: gps[0]
            });
        markers.push(marker);

        // Add a new infowindow
        var infowindow = new google.maps.InfoWindow({
            content: "Datetime: " + gps[1]
        });
        marker.addListener('click', function() {
            infowindow.open(map, marker);
        });
}
Federico
  • 55
  • 1
  • 7

1 Answers1

1

To remove markers from the map, set their map property to null (not map).

This:

 markers[i].setMap(map);

should be:

markers[i].setMap(null);

Your question about infoWindows is a duplicate of Google Maps JS API v3 - Simple Multiple Marker Example (you only have one marker variable in your code when the loop completes currently, you can use function closure to associate the click listener with each individual marker created on the map).

Community
  • 1
  • 1
geocodezip
  • 158,664
  • 13
  • 220
  • 245