Google Maps API JS несколько маркеров, используя поля ввода? - PullRequest
0 голосов
/ 12 июня 2018

Я хочу, чтобы я мог показывать несколько маркеров, когда я вставляю что-то в окна поиска на сайте.Прямо сейчас у меня есть 3 поля ввода, которые я хочу увеличить.Это то, что у меня сейчас есть, я пытался сохранить несколько значений searchBox в var, например, так: var markers = searchBox.getPlaces(), searchBox.getPlaces1(), searchBox.getPlaces2()

Как расширить этот код для дополнительных полей ввода?

<input id="pac-input" class="controls" type="text" placeholder="Search Box" /><br />
<input id="pac-input1" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input2" class="controls" type="text" placeholder="Search box" />
<div id="map"></div>
<script>
    function initAutocomplete() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: 52.728616, lng: 6.4901 },
            zoom: 13,
            mapTypeId: 'roadmap'
        });

        // Create the search box and link it to the UI element.
        var input = document.getElementById('pac-input');
        var input1 = document.getElementById('pac-input1');
        var input2 = document.getElementById('pac-input2');
        var searchBox = new google.maps.places.SearchBox(input);
        var searchBox1 = new google.maps.places.SearchBox(input1);
        var searchBox2 = new google.maps.places.SearchBox(input2);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input1);

        // Bias the SearchBox results towards current map's viewport.
        map.addListener('bounds_changed', function () {
            searchBox.setBounds(map.getBounds());
            searchBox1.setBounds(map.getBounds());
            searchBox2.setBounds(map.getBounds());
        });

        var markers = [];

        searchBox.addListener('places_changed', function () {
            var places = searchBox.getPlaces();

            if (places.length == 0) {
                return;
            }

            // Clear out the old markers.
            markers.forEach(function (marker) {
                marker.setMap(null);
            });
            markers = [];

            // For each place, get the icon, name and location.
            var bounds = new google.maps.LatLngBounds();
            places.forEach(function (place) {
                if (!place.geometry) {
                    console.log("Returned place contains no geometry");
                    return;
                }
                var icon = {
                    url: place.icon,
                    size: new google.maps.Size(71, 71),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(25, 25)
                };

                // Create a marker for each place.
                markers.push(new google.maps.Marker({
                    map: map,
                    icon: icon,
                    title: place.name,
                    position: place.geometry.location
                }));

                if (place.geometry.viewport) {
                    // Only geocodes have viewport.
                    bounds.union(place.geometry.viewport);
                } else {
                    bounds.extend(place.geometry.location);
                }
            });
            map.fitBounds(bounds);
        });
    }

</script>
<script src="https://maps.googleapis.com/maps/api/js?key=[APIKEY]&libraries=places&callback=initAutocomplete"
        async defer></script>

1 Ответ

0 голосов
/ 12 июня 2018

связанный вопрос (для автозаполнения): Google Maps API автоматически заполняет 2-е поля адреса на той же странице

Получите массив <input> элементов, которые вы хотите использовать для SearchBox,используйте их для создания объектов SearchBox, создания функции, которая принимает уникальный идентификатор для SearchBox и ссылку на объект SearchBox.Используйте эту функцию для обработки событий от каждого из SearchBox объектов.

var searchBoxes = document.getElementsByClassName('controls');
for (var i=0; i<searchBoxes.length;i++) {
  var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBoxes[i]);
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });
  markers.push([]);
  searchBox.addListener('places_changed', (function(i) {
    return function() {
      processSearch(i, this)
    }
  }(i)));
}

Функция processSearch:

function processSearch(uniqueId, searchBox) {
  var places = searchBox.getPlaces();

  if (places.length == 0) {
    return;
  }

  // Clear out the old markers.
  markers[uniqueId].forEach(function(marker) {
    marker.setMap(null);
  });
  markers[uniqueId] = [];

  // For each place, get the icon, name and location.
  var bounds = new google.maps.LatLngBounds();
  places.forEach(function(place) {
    if (!place.geometry) {
      console.log("Returned place contains no geometry");
      return;
    }
    var icon = {
      url: place.icon,
      size: new google.maps.Size(71, 71),
      origin: new google.maps.Point(0, 0),
      anchor: new google.maps.Point(17, 34),
      scaledSize: new google.maps.Size(25, 25)
    };

    // Create a marker for each place.
    if (!markers[uniqueId]) markers.push([]);
    markers[uniqueId].push(new google.maps.Marker({
      map: map,
      icon: icon,
      title: place.name,
      position: place.geometry.location
    }));

    if (place.geometry.viewport) {
      // Only geocodes have viewport.
      bounds.union(place.geometry.viewport);
    } else {
      bounds.extend(place.geometry.location);
    }
  });
  map.fitBounds(bounds);
}

подтверждение концепции скрипта

screenshot of resulting map

фрагмент кода:

html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}

.controls {
  width: 100px;
}
<input id="pac-input" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input1" class="controls" type="text" placeholder="Search Box" />
<input id="pac-input2" class="controls" type="text" placeholder="Search box" />
<input id="pac-input3" class="controls" type="text" placeholder="Search box" />
<input id="pac-input4" class="controls" type="text" placeholder="Search box" />
<input id="pac-input5" class="controls" type="text" placeholder="Search box" />

<div id="map"></div>
<script>
  function initAutocomplete() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: {
        lat: 52.728616,
        lng: 6.4901
      },
      zoom: 13,
      mapTypeId: 'roadmap'
    });
    var markers = [];

    // Create the search boxs and link them to the UI elements.
    var searchBoxes = document.getElementsByClassName('controls');
    for (var i = 0; i < searchBoxes.length; i++) {
      var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(searchBoxes[i]);
      map.addListener('bounds_changed', function() {
        searchBox.setBounds(map.getBounds());
      });
      markers.push([]);
      searchBox.addListener('places_changed', (function(i) {
        return function() {
          processSearch(i, this)
        }
      }(i)));
    }

    function processSearch(uniqueId, searchBox) {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      // Clear out the old markers.
      markers[uniqueId].forEach(function(marker) {
        marker.setMap(null);
      });
      markers[uniqueId] = [];

      // For each place, get the icon, name and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        if (!place.geometry) {
          console.log("Returned place contains no geometry");
          return;
        }
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };

        // Create a marker for each place.
        if (!markers[uniqueId]) markers.push([]);
        markers[uniqueId].push(new google.maps.Marker({
          map: map,
          icon: icon,
          title: place.name,
          position: place.geometry.location
        }));

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
      map.fitBounds(bounds);
    }
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete" async defer></script>
...