Jemai
Jemai

Reputation: 2849

Toggle markers in google map using radio button

I have 4 cities in los angeles and I have 5 radio buttons and If I want to click each markers it will show or hide specific markers or show all the markers, how can I accomplish that?

Here's the code

 var map;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: 34.052235, lng: -118.243683},
      zoom: 11
    });
    setMarkers(map);
  }

  var cities = [
        ['Compton Los Angeles', 33.895847, -118.220070],
        ['Huntington Los Angeles', 33.984932, -118.227821],
        ['Los Angeles International Airport',33.942791, -118.410042],
        ['Beverly Hills Los Angeles',34.073620, -118.400352]
  ];

  function setMarkers(map) {
        for (var i = 0; i < cities.length; i++) {
            var city = cities[i];
            var marker = new google.maps.Marker({
              position: {lat: city[1], lng: city[2]},
              map: map
            }); 
      }
  }

<input id="compton" type="radio" name="city" checked="checked">
<input id="huntington" type="radio" name="city">
<input id="losangeles" type="radio" name="city">
<input id="beverlyhills" type="radio" name="city">
<input id="showall" type="radio" name="city">

Upvotes: 0

Views: 1354

Answers (2)

Илья Зелень
Илья Зелень

Reputation: 8108

I answered this in the Russian portal HERE.

Google Translate:

The markers are divided into groups in the myMarkers object, each key is the name of the group, and each value is the group object in which the keys are the marker headers, and the value is the marker coordinates.

In each group there can be options, in options you can set any parameters that will be applied to each group marker, in this example there are icons and animations in the options.

The googleMarkers object is structured like myMarkers, but it contains the Google markers objects, and not their description, this object is populated in the setMarkers function.

Radio buttons are tied to groups by the data- * attribute, this allows you to use an arbitrary id for the element. Initially, those markers that relate to the radio button that is checked are displayed. A radio button with data-marker = "showall" shows all the elements.

The rest should be understandable, there are comments in the code and ES2015 is used.

let map, googleMarkers = {} // карта и объект содержащий объекты гугл маркеров
const radios = document.querySelectorAll('input[type=radio][data-marker]')
const myMarkers = { // описание маркеров
  first: {
    'Title 1': [52.4357808, 4.991315699999973],
  },
  second: { // имя группы
    options: { // опции для маркеров этой группы
      icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png' 
    }, 
    'Title 2': [52.4357808, 4.981315699999973],
    'Title 3': [52.4555687, 5.039231599999994],
  },
  third: {
    options: { 
      icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
      animation: google.maps.Animation.BOUNCE
    },
    'Title 4': [52.4755687, 5.019261599999994],
    'Title 5': [52.4555687, 5.049231599999994],
    'Title 6': [52.4055687, 5.039236599999994]
  }
}

initMap()
// для каждой радио-кнопки добавляет слушатель события клика
radios.forEach(i => i.addEventListener('click', radioClick))


function initMap() {
  const center = new google.maps.LatLng(52.4527808, 4.991315699999973)
  const mapOptions = {
    zoom: 11,
    center,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  }

  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions)
  setMarkers(map)
}

function setMarkers (map) {
  let isFirst = true
  for (let group in myMarkers) {
    for (let title in myMarkers[group]) {
      if (title === 'options') // не берет во внимание опции
        continue
   
      const myMarker = myMarkers[group][title]
      const visible = document.querySelector(`input[type=radio][data-marker=${group}]`).checked
      const marker = new google.maps.Marker({
        title,
        position: {lat: myMarker[0], lng: myMarker[1]},
        map,
        visible,
        ...myMarkers[group].options // берет опции группы
      })
      
      googleMarkers[group] = googleMarkers[group] || [] // создает массив если его нет
      googleMarkers[group].push(marker)
    }
  }
}

function radioClick ({ target }) { // берет target события
  const group = target.dataset.marker // id группы к которой принадлежит радио-кнопка
  const arrOfEveryGroup = Object.values(googleMarkers) // массив массивов групп маркеров
  const everyMarker = [].concat.apply([], arrOfEveryGroup) // массив всех маркеров
  
  if (group === 'showall') {
    // показывает всех
    everyMarker.forEach(i => i.setVisible(true))
    return
  }
  // те кто был видимым становиться не видемым
  everyMarker.forEach(i => i.visible && i.setVisible(false))
  
  // показывает группу к которой принадлежит радио-кнопка
  for (let marker of googleMarkers[group])
    marker.setVisible(!marker.visible)
}
#map-canvas { 
  height: 160px;
  width: 100%;
}
#map-canvas img {
  max-width: none;
}
    
#map-canvas div {
  -webkit-transform: translate3d(0, 0, 0);
}
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>


<div id="map-canvas" ></div>


<input data-marker="first" id="first" type="radio" name="myMarkers">
<label for="first">First</label>

<input data-marker="second" id="second" type="radio" name="myMarkers" checked>
<label for="second">second</label>

<input data-marker="third" id="third" type="radio" name="myMarkers">
<label for="third">third</label>

<input data-marker="showall" id="showall" type="radio" name="myMarkers">
<label for="showall">Show all</label>

Upvotes: 0

Constantine
Constantine

Reputation: 554

          google.maps.event.addListener(marker, 'click', function() {
                // Show\hide radio-btns
                document.getElementById("showall").style.display = 'none';
                document.getElementById("compton").style.display = 'inline';
                // Hide marker
                this.setVisible(false); // maps API hide call
                // or
                markers[2].setVisible(false);
          });

JSFiddle: http://jsfiddle.net/4a87k/857/ (updated)

It is how to add onclick event on markers: adding-an-onclick-event-to-google-map-marker

Upvotes: 3

Related Questions