Переключение функций слоя данных API Карт Google с помощью внешних кнопок на основе свойств объектов - PullRequest
1 голос
/ 14 марта 2019

В документации для Уровня данных API Карт Google - Динамическая стилизация объясняется, как добавить прослушиватель событий для функции, чтобы при щелчке по этой функции мы могли изменить ее свойство.

Как сделать что-то похожее с кнопкой, внешней по отношению к карте? В примере с скрипкой, как я могу превратить буквы на карте, которые имеют свойство "синий", в синий, нажав синюю кнопку?

Пример скрипки

<!DOCTYPE html>
<html>
  <head>
    <title>Data Layer: Dynamic Styling</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <style>#map {
    height: 500px;
  }
  </style>
  </head>
  <body>
<button id="blue-button">blue</button>
<button id="red-button">red</button>
<button id="green-button">green</button>
<button id="yellow-button">yellow</button>
<div id="map"></div>
    <script>

      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: {lat: -28, lng: 137}
        });

        // Load GeoJSON.
        map.data.loadGeoJson(
            'https://storage.googleapis.com/mapsdevsite/json/google.json');

        // Color each letter gray. Change the color when the isColorful property
        // is set to true.
        map.data.setStyle(function(feature) {

          var color = 'gray';

          if (feature.getProperty('isColorful')) {
            color = feature.getProperty('color');
            console.log(color)
          }

          return ({
            fillColor: color,
            strokeColor: color,
            strokeWeight: 2
          });

        });

        // When the user clicks, set 'isColorful', changing the color of the letters.
        map.data.addListener('click', function(event) {
          event.feature.setProperty('isColorful', true);
        });

      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB9BG3aO_hV9r8qaGkYmcE5eSx7c4K7be4&callback=initMap">
    </script>
  </body>
</html>

1 Ответ

1 голос
/ 14 марта 2019

Добавьте слушателя для вашего нажатия кнопки.Это можно сделать разными способами.Одним из них является использование Google Maps addDomListener.

. Затем необходимо выполнить цикл по всем функциям и установить соответствующий стиль, например:

.

var map;

function initMap() {

  map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 4,
    center: {
      lat: -28,
      lng: 137
    }
  });

  // Load GeoJSON.
  map.data.loadGeoJson(
    'https://storage.googleapis.com/mapsdevsite/json/google.json');

  // Color each letter gray. Change the color when the isColorful property
  // is set to true.
  map.data.setStyle(function(feature) {

    var color = 'gray';

    if (feature.getProperty('isColorful')) {
      color = feature.getProperty('color');
      console.log(color)
    }

    return ({
      fillColor: color,
      strokeColor: color,
      strokeWeight: 2
    });

  });

  // When the user clicks, set 'isColorful', changing the color of the letters.
  map.data.addListener('click', function(event) {
    event.feature.setProperty('isColorful', true);
  });

  google.maps.event.addDomListener(document.getElementById('blue-button'), 'click', function() {

    map.data.setStyle(function(feature) {

      if (feature.getProperty('color') == 'blue') {

        return ({
          fillColor: 'blue',
          strokeColor: 'blue',
          strokeWeight: 2
        });
      } else {

        return ({
          fillColor: 'grey',
          fillOpacity: .5,
          strokeColor: 'grey',
          strokeWeight: 2
        });
      }
    });
  });

}
#map-canvas {
  height: 160px;
}
<button id="blue-button">blue</button>
<div id="map-canvas"></div>

<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...