javascript – Hide/Show markers on Google Map

Question:

There is a set of markers plotted on a google map. I thought to set up hiding / showing markers via jquery by the id of each marker (well, or by class).

google.maps.event.addDomListener(window, 'load', init);

function init() {
    var mapOptions = {
        zoom: 15,
        center: new google.maps.LatLng(43.229682, 76.955123),
    };

    var mapElement = document.getElementById('map');

    var map = new google.maps.Map(mapElement, mapOptions);

    var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
    var icons = {
      office: {
        icon: '../images/map_icons/st_marker.png'
      },
      detskiy_sad: {
        icon: '../images/map_icons/detskiy-sad.png'
      },
      study: {
        icon: '../images/map_icons/study.png'
      },
      medical: {
        icon: '../images/map_icons/medical.png'
      },
      sport: {
        icon: '../images/map_icons/sport.png'
      },
      trade_center: {
        icon: '../images/map_icons/trade-center.png'
      }
    };

    var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(43.229859, 76.955320),
        map: map,
        icon: icons['office'].icon,
        title: 'Жилой комплекс Samal Tower'
    });
    var marker_detsad1 = new google.maps.Marker({
        position: new google.maps.LatLng(43.231395, 76.953998),
        map: map,
        icon: icons['detskiy_sad'].icon,
        title: 'Ясли-сад №114'
    }); 
...

I can’t find in the manuals how to set the id parameter for a specific marker.

Answer:

The answer to this question is on the English CO: https://stackoverflow.com/questions/3219437/google-maps-marker-grouping

The issue can be resolved as follows:

  • We start the markers array, where we save all the created markers
  • When creating each marker, add the type field
  • To hide/show markers of a certain category, we bypass the markers array and, based on the type of each marker, we change the visibility using markers[i].setVisible(true/false);

In your case it will be something like this:

// ........  
var markers = [];

var marker_office1 = new google.maps.Marker({
    position: new google.maps.LatLng(43.229859, 76.955320),
    map: map,
    icon: icons['office'].icon,
    title: 'Жилой комплекс Samal Tower'
});
marker_office1.type = 'office';
markers.push(marker_office1);

var marker_detsad1 = new google.maps.Marker({
    position: new google.maps.LatLng(43.231395, 76.953998),
    map: map,
    icon: icons['detskiy_sad'].icon,
    title: 'Ясли-сад №114'
}); 
marker_detsad1.type = 'detskiy_sad';
markers.push(marker_detsad1);

function displayMarkers(type) {
    for (var i = 0; i < markers.length; i++) {
        if (markers[i].type === type) {
            markers[i].setVisible(true);
        } else {
             markers[i].setVisible(false);
        } 
    }
}
Scroll to Top