-1

Looking to clear all marker clusters using on click from a floating panel. I can clear and show all markers but not the marker clustered icons. I have scoured through multiple similar questions but am missing something for sure.

When I try to use the below code it comes back with markerCluster is not defined at clearMarkers.

JS Code:

var map;
var geocoder;
var markerAll;
var markers = [];

//Code to load the map with center point of Monterey MA
function initMap() {
    var monterey = {lat: 42.181613, lng: -73.215013};
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 10,
        center: monterey,
        mapTypeId: google.maps.MapTypeId.HYBRID,
        labels: true,
    });

    //collect customer data and geocoder object - declare geocoder as global
    var cusdata = JSON.parse(document.getElementById('data').innerHTML);
    geocoder = new google.maps.Geocoder();  
    codeAddress(cusdata);

    var allData = JSON.parse(document.getElementById('allData').innerHTML);
    showAllCustomers(allData);

    var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
    showSearchedCustomer(searchData);
    
}

function showAllCustomers(allData) {
    //declare info window variable outside of loop to allow to clear when selecting other markers
    var infoWind = new google.maps.InfoWindow;

    //Create marker clusterer to group data
    var markerCluster = new MarkerClusterer(map, [], {
        imagePath: 'images/m'
      });


    Array.prototype.forEach.call(allData, function(data){
        var content = document.createElement('div');
        var strong = document.createElement('strong');
        
        strong.textContent = [data.lastName + ' ' + data.physicalAddress];
        content.appendChild(strong);

        //add image to infowindow - you are also able to add image path to mysql and then append dynamically
        // var img = document.createElement('img');
        // img.src = 'images/santahat.png';
        // img.style.width = '50px';
        // content.appendChild(img);

        //Create markers for customer locations and customize
        var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
          var markerAll = new google.maps.Marker({
          position: new google.maps.LatLng(data.latitude, data.longitude),
          map: map,
          icon: iconBase + 'homegardenbusiness.png'
        });

        //push markers to marker clusterer
        markerCluster.addMarker(markerAll);
        markers.push(markerAll);

    }) 

}

// Sets the map on all markers in the array.
function setMapOnAll(map) {
    for (let i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }
  // Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
    setMapOnAll(null);
    markerCluster.clearMarkers(markerAll);  <----- THIS IS WHAT I TRIED TO ADD TO CLEAR CLUSTERS
}
  
  // Shows any markers currently in the array.
  function showMarkers() {
    setMapOnAll(map);
  }
  
geocodezip
  • 158,664
  • 13
  • 220
  • 245
bodenbox
  • 5
  • 4
  • 1
    `markerCluster` variable is defined in your `showAllCustomers` function and therefore is not available in your `clearMarkers` functions. See https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – MrUpsidown Dec 15 '20 at 16:33
  • you need to hoist `markerCluster` to the top level, then assign to it. that way it will be in scope for `clearMarkers` – r3wt Dec 15 '20 at 16:33
  • How are you calling the `clearMarkers` routine? – geocodezip Dec 15 '20 at 17:05

1 Answers1

1

You need to put the markerCluster in the global scope so it can be used in the clearMarkers function (which is (probably) defined in the the global scope).

var markerCluster;
function showAllCustomers(allData) {
    //Create marker clusterer to group data
    markerCluster = new MarkerClusterer(map, [], {
        imagePath:
      "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
      });

proof of concept fiddle

code snippet:

var map;
var geocoder;
var markerAll;
var markers = [];

//Code to load the map with center point of Monterey MA
function initMap() {
  var monterey = {
    lat: 42.181613,
    lng: -73.215013
  };
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 3,
    center: {
      lat: -28.024,
      lng: 140.887
    },
    mapTypeId: google.maps.MapTypeId.HYBRID,
    labels: true,
  });

  //collect customer data and geocoder object - declare geocoder as global
  var cusdata = JSON.parse(document.getElementById('data').innerHTML);
  geocoder = new google.maps.Geocoder();
  // codeAddress(cusdata);

  var allData = JSON.parse(document.getElementById('allData').innerHTML);
  allData = locations;
  showAllCustomers(allData);

  var searchData = JSON.parse(document.getElementById('searchData').innerHTML);
  // searchData = locations;
  // showSearchedCustomer(searchData);

}
var markerCluster;

function showAllCustomers(allData) {
  //Create marker clusterer to group data
  markerCluster = new MarkerClusterer(map, [], {
    imagePath: 'https://unpkg.com/@google/markerclustererplus@4.0.1/images/m',
  });

  //declare info window variable outside of loop to allow to clear when selecting other markers
  var infoWind = new google.maps.InfoWindow;
  Array.prototype.forEach.call(allData, function(data) {
    var content = document.createElement('div');
    var strong = document.createElement('strong');

    strong.textContent = [data.lastName + ' ' + data.physicalAddress];
    content.appendChild(strong);

    //add image to infowindow - you are also able to add image path to mysql and then append dynamically
    // var img = document.createElement('img');
    // img.src = 'images/santahat.png';
    // img.style.width = '50px';
    // content.appendChild(img);

    //Create markers for customer locations and customize
    var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
    var markerAll = new google.maps.Marker({
      position: new google.maps.LatLng(data.latitude, data.longitude),
      map: map,
      // icon: iconBase + 'homegardenbusiness.png'
    });

    //push markers to marker clusterer
    markerCluster.addMarker(markerAll);
    markers.push(markerAll);
  })
  google.maps.event.addDomListener(document.getElementById('btn'), 'click', clearMarkers);
}

// Sets the map on all markers in the array.
function setMapOnAll(map) {
  for (let i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setMapOnAll(null);
  markerCluster.clearMarkers(markerAll);
}

// Shows any markers currently in the array.
function showMarkers() {
  setMapOnAll(map);
}

const locations = [{
    latitude: -31.56391,
    longitude: 147.154312,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -33.718234,
    longitude: 150.363181,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -33.727111,
    longitude: 150.371124,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -33.848588,
    longitude: 151.209834,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -33.851702,
    longitude: 151.216968,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -34.671264,
    longitude: 150.863657,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -35.304724,
    longitude: 148.662905,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -36.817685,
    longitude: 175.699196,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -36.828611,
    longitude: 175.790222,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -37.75,
    longitude: 145.116667,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -37.759859,
    longitude: 145.128708,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -37.765015,
    longitude: 145.133858,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -37.770104,
    longitude: 145.143299,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -37.7737,
    longitude: 145.145187,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -37.774785,
    longitude: 145.137978,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -37.819616,
    longitude: 144.968119,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -38.330766,
    longitude: 144.695692,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -39.927193,
    longitude: 175.053218,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -41.330162,
    longitude: 174.865694,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -42.734358,
    longitude: 147.439506,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -42.734358,
    longitude: 147.501315,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -42.735258,
    longitude: 147.438,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
  {
    latitude: -43.999792,
    longitude: 170.463352,
    lastName: "Smith",
    physicalAddress: "New York, NY"
  },
];
/* 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;
}
<!DOCTYPE html>
<html>

<head>
  <title>Marker Clustering</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js"></script>
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <input id="btn" type="button" value="Clear Markers" />
  <div id="map"></div>
  <div id="data">[]</div>
  <div id="allData">[]</div>
  <div id="searchData">[]</div>
</body>

</html>
geocodezip
  • 158,664
  • 13
  • 220
  • 245